python - Python:复数的 Exp 不起作用
问题描述
我对 Python 非常陌生,通常使用 MATLAB 编写代码,因此我尝试创建这个在 for 循环中具有 exp(复数)的小代码。(我需要 for 循环,因为我在代码中有多维矩阵)。
每次我添加术语 (1j*) 时,代码都不起作用,并显示以下错误
TypeError: can't convert complex to float
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
, line 17, in <module>
Zx[n,m] =np.exp(1j*np.pi*(m)*np.sin(theta[:,n])*np.sin(phi[:,n]))
ValueError: setting an array element with a sequence.
这是代码
import numpy as np
M=4
N=5
Zx = np.zeros([N,M])
theta = np.pi*np.random.rand(1,N)
phi = 2*np.pi*np.random.rand(1,N)
for n in range(N):
for m in range(M):
Zx[n,m] =np.exp(1j*np.pi*(m)*np.sin(theta[:,n])*np.sin(phi[:,n]))
可能是什么原因?谢谢
解决方案
默认情况下,np.zeros
创建一个类型为 的数组np.float64
。如果您尝试将复杂值分配给此类数组的元素,则会收到错误消息TypeError: can't convert complex to float
。
如果你制作Zx
一个复数数组,你的代码就可以工作:
Zx = np.zeros([N, M], dtype=complex)
仅供参考:您可以使用广播来消除代码中的 Python for 循环:
M = 4
N = 5
theta = np.pi*np.random.rand(1, N)
phi = 2*np.pi*np.random.rand(1, N)
m = np.arange(M)
Zx = np.exp(1j*np.pi*m*np.sin(theta.T)*np.sin(phi.T))
推荐阅读
- php - 无法在不冻结浏览器的情况下使用 HTTP post/get 请求启动独立的后台长任务
- java - 使用 ForEach 循环从 List 中查找最后一个元素
- android - 发送数据更改通知
- javascript - 带有rects的SVG溢出父div而不是缩放高度以尝试适应屏幕尺寸
- r - 如何删除不符合 R 中参数的列?
- javascript - 在所需的附录检查功能中减少 JS 数组值时出错
- python - 在开发环境中从同一命名空间引用 python 包
- php - 在单击提交按钮之前显示消息
- c - 需要帮助确定我需要更改什么以实施所需的更改
- graph - neo4j 找到所有发布了我喜欢的东西的朋友