Python numpy 的复数问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20078700/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Complex number troubles with numpy
提问by elefun
I'm attempting to translate some matlab code again and I've run into another pickle. The code itself is very simple, it's just a demonstration of a 4 node twiddle factor. Here is my attempt:
我试图再次翻译一些 matlab 代码,但我遇到了另一个泡菜。代码本身非常简单,它只是一个4节点旋转因子的演示。这是我的尝试:
from numpy import *
from matplotlib import pyplot as plt
x = zeros(4)
x[-1+1] = 0
x[0+1] = 1
x[1+1] = 1
x[2+1] = 0
z = 0 - 1j
W4 = exp(z*2*pi/4)
W0 = W4 ** 0
W1 = W4 ** 1
W2 = W4 ** 2
W3 = W4 ** 3
X = zeros(4)
X[-1+1] = (x[-1+1] + x[1+1]*W0) + W0*(x[0+1] + x[2+1]*W0)
X[0+1] = (x[-1+1] + x[1+1]*W2) + W1*(x[0+1] + x[2+1]*W2)
X[1+1] = (x[-1+1] + x[1+1]*W0) + W2*(x[0+1] + x[2+1]*W0)
X[2+1] = (x[-1+1] + x[1+1]*W2) + W3*(x[0+1] + x[2+1]*W2)
fx = fft.fft(x)
plt.plot(X)
plt.plot(fx, 'ro')
plt.title("Results 4-point hand programmed FFT (blue) and the PYTHON routine (red o)")
plt.show()
Here are the output images. The first one is run with (almost) identical matlab code, the second one is the image from the python code above.

这是输出图像。第一个使用(几乎)相同的 matlab 代码运行,第二个是来自上面 python 代码的图像。

For lines 24 to 27 it gives me the error "ComplexWarning: Casting complex values to real discards the imaginary part". Now I'm not used to working with complex numbers in python. I tried adding a complex component to all the variables, but it gave me a graph that's way off from the matlab one. Thoughts? If you would like me to post the matlab code as well, let me know.
对于第 24 到 27 行,它给了我错误“ComplexWarning:将复数值转换为实数会丢弃虚部”。现在我不习惯在 python 中处理复数。我尝试为所有变量添加一个复杂的组件,但它给了我一个与 matlab 相去甚远的图表。想法?如果您也希望我发布 matlab 代码,请告诉我。
采纳答案by atomh33ls
When you specify the array xand Xyou need to make sure it is of complex data type, i.e:
当您指定数组x并且X需要确保它是复杂数据类型时,即:
x = zeros((4),dtype=complex)
EDIT:
编辑:
To fix the plot you need to plot both real and imaginary parts:
要修复绘图,您需要绘制实部和虚部:
plt.plot(X.real,X.imag)
plt.plot(fx.real,fx.imag, 'ro')
This gives me:
这给了我:


....which looks like your Matlab graph.
....这看起来像你的 Matlab 图。

