为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用 python 绘制二次函数虚数输入的 4 维图

如何使用 python 绘制二次函数虚数输入的 4 维图

三国纷争 2023-12-29 14:37:04
我是一名高中生,没有编码经验,但我尝试编写一个 matplotlib 3d 图形,并以颜色渐变作为第四维来绘制函数图:f(x) = x^2 + 1对于x的所有实数和复数值 (a + b i ) ,这需要我有四个维度:x的 (x + bi) 的实部 x [现在称为 X] , ( x + bi) [现在称为W],(y + bi) 的实部y [现在称为Y],以及(y + bi) 的虚部bi [现在称为Z]。基本上,输入将为x,格式为(X + W),输出将为f(x),格式为(Y + Z)。我希望图表具有 X、Y 和 Z 轴,W 表示为图表表面上的颜色渐变。Z 和 W 是虚数 b*cmath.sqrt(-1)。我想要所有参数的范围为 (-20, 20)。我的笔记本电脑上有 python 和 anaconda,请帮忙。<3
查看完整描述

1 回答

?
守着星空守着你

TA贡献1799条经验 获得超8个赞

这是我的解决方案:


# Import packages

import numpy as np

from mpl_toolkits.mplot3d import Axes3D   # Needed to create 3D plots

import matplotlib

import matplotlib.pyplot as plt

#%matplotlib notebook                     # Uncomment this if using Jupyter


# Define function

def fun(x):

    # Note: x is a complex() object, and * and + are defined for complex numbers

    return x*x + 1


# Create 1x1 figure with 3 axes

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')


# Define grid of x and w using a step of 0.05

X = W = np.arange(-20.0, 20.0, 0.05)

X, W = np.meshgrid(X,W)

complexVals = X + 1j*W      # Convert X/W grid into complex numbers


# Call the function on the complex numbers and extract the real/imag parts

Y_Z = fun(complexVals)

Y = Y_Z.real

Z = Y_Z.imag


# Create colormap for W

color_dimension = W

minn, maxx = color_dimension.min(), color_dimension.max()

norm = matplotlib.colors.Normalize(minn, maxx)

m = plt.cm.ScalarMappable(norm=norm, cmap='jet')

m.set_array([])

fcolors = m.to_rgba(color_dimension)


# Create surface

ax.plot_surface(X, Y, Z, facecolors=fcolors, vmin=minn, vmax=maxx, shade=False,

                linewidth=0, antialiased=False)


# Set axis labels

ax.set_xlabel('X (Re)')

ax.set_ylabel('Y (Re)')

ax.set_zlabel('Z = f(x) (Im)')


# Create colorbar and set title

cbr = plt.colorbar(m)

cbr.ax.set_title('W')


# Show plot with colorbar

plt.show()

这是输出:

https://img1.sycdn.imooc.com/658e69a10001511906100476.jpg

但是,如果您使用 Anaconda,我强烈建议将此代码添加到 Jupyter Notebook 中。这就是你可以获得交互式情节的原因。
它已经随 Anaconda 一起安装,您可以通过jupyter notebook在 Anaconda 提示符中输入来启动它。

查看完整回答
反对 回复 2023-12-29
  • 1 回答
  • 0 关注
  • 51 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信