python - 使用 Matplotlib 进行 3D 绘图时 cmath 的问题

标签 python python-3.x matplotlib 3d cmath

我有这个简单的代码,它试图获取两个复数 E1E2 实部的 3D 图作为 t 的函数> 和 g

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import cmath


eps=0.5


def ReE1(t,g):
    E1=eps+cmath.sqrt(t**2-g**2)
    return E1.real 

def ReE2(t,g):
    E2=eps-cmath.sqrt(t**2-g**2)
    return E2.real 



fig = plt.figure()
ax = plt.axes(projection="3d")

t = np.linspace(0, 10, 50)
g = np.linspace(0, 10, 50)

X, Y = np.meshgrid(t, g)
Z = ReE1(X, Y)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1,
                cmap='winter', edgecolor='none')
Z = ReE2(X, Y)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1,
                cmap='summer', edgecolor='none')
plt.show()

我在使用 Python 3 运行时遇到以下错误。

Traceback (most recent call last):
  File "t2.py", line 28, in <module>
    Z = ReE1(X, Y)
  File "t2.py", line 11, in ReE1
    E1=eps+cmath.sqrt(t**2-g**2)
TypeError: only length-1 arrays can be converted to Python scalars

我们该如何解决这个问题?另外,我们可以直接使用复杂函数E1E2(而不是ReE1ReE2)并调用绘图时的 real 模块?

最佳答案

问题似乎是 cmath 中的 sqrt 仅接受标量,而您试图通过为其提供二维数组来以矢量化方式使用它。一种解决方案是通过循环遍历 tg 的每个元素,对它们应用 cmath.sqrt,如下所示:

def ReE1(t,g):
    E1 = np.zeros(t.shape, dtype='complex')    
    for i in range(t.shape[0]):
        for j in range(t.shape[1]):
            E1[i][j]=eps+cmath.sqrt(t[i][j]**2-g[i][j]**2)
    return E1.real 

def ReE2(t,g):
    E2 = np.zeros(t.shape, dtype='complex')    
    for i in range(t.shape[0]):
        for j in range(t.shape[1]):
            E2[i][j]=eps-cmath.sqrt(t[i][j]**2-g[i][j]**2)
    return E2.real 

enter image description here

关于python - 使用 Matplotlib 进行 3D 绘图时 cmath 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58125000/

相关文章:

python - pytest:如何获取从模拟类返回的(模拟)实例?

python - 将文本添加到 matplotlib 绘图时自动调整绘图限制

python - 如何匹配python中运行时间太长的所有键值对

python - 在 Jinja 中使用嵌入的 HTML 渲染 WTForms SelectField 选项

python - 使用 Nginx 的 Flask?

python - 如何按周显示数据并显示周数?

python - 使用python将IP范围划分为1024 block

python - 在 matplotlib 中绘制时间图的 X 代码问题

python - Seaborn light_palette 自定义长度

python - 使用 rootpy 和 matplotlib 绘制二维直方图