首页 > 解决方案 > 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]))

可能是什么原因?谢谢

标签: pythonnumpy

解决方案


默认情况下,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))

推荐阅读