用matplotlib实现comlex函数

时间:2018-12-17 18:03:56

标签: python numpy matplotlib

如何使用matplotlib和numpy实现此功能?

1 /(a + jw)^ 2

下面的代码有什么问题?!

# a+jw

import matplotlib.pyplot as plt
from numpy import pi, exp, real, imag, linspace

def f(a, w):
    return a + 1j*w

w = linspace(0, 2*pi, 1000)
a = linspace(0, 2, 1000)
plt.plot(real(f(a,w), imag(f(a, w))

plt.show()

2 个答案:

答案 0 :(得分:1)

f(a,w)给出[x+ j*y for (x,y) in zip(a,w)],因此real(f(a,w))给出精确的a,而image给出精确的w。您将从plt.plot()得到一条直线。

这里需要修复一些代码。是您期望的吗?

def f(a, w):
    # your function just returns the complex number with real=a and imag=w without power -2
    return (a + 1j*w)**-2

# test case
print(f(1,1), f(1,0)) # should yeild -0.5j, 1

# either w or a must start from non-zero value for inverse to work
w = linspace(0.01, 2*pi, 1000) 
a = linspace(0.01, 2, 1000) 
plt.plot(real(f(a,w)), imag(f(a, w)))

plt.show()

这是情节的输出: enter image description here

答案 1 :(得分:1)

import matplotlib.pyplot as plt
from numpy import pi, exp, real, imag, linspace
def f(w, a = 5):
    return (a + 1j*w)**-2


w = linspace(0.01, 2*pi, 1000) 
ys = [np.sqrt(imag(f(x)) ** 2 + real(f(x)) ** 2 ) for x in w ]

plt.plot(w, ys)

plt.show()