使用Matplotlib进行三维打印时的cmath问题

2024-10-03 13:22:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的代码,它试图得到两个复数的实部的3D图E1E2,作为tg的函数

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()

在运行python3时出现以下错误

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模块吗


Tags: 函数importdefasnppltsqrteps
1条回答
网友
1楼 · 发布于 2024-10-03 13:22:09

问题似乎是来自cmathsqrt只接受标量,而您正试图通过为它提供一个二维数组来以矢量化的方式使用它。一种解决方案是通过如下循环在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

相关问题 更多 >