对于傅里叶级数方程的循环

时间:2015-09-23 21:37:52

标签: python numpy

如何使用for循环绘制下面的傅立叶级数方程式,我可以更改n,而不是写出cos(x) + cos(2x) + cos(3x)等?

我的脚本如下:

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
pi  = np.pi
x = np.linspace(-pi,pi,100)
ao = (1/(2*pi))
y = ao + (1/pi)*(np.cos(x)+np.cos(2*x)+np.cos(3*x) + np.cos(4*x)+np.cos(5*x)+np.cos(6*x) + np.cos(7*x) + np.cos(8*x) + np.cos(9*x)+np.cos(10*x))

plt.plot(x,y)
plt.show()

2 个答案:

答案 0 :(得分:5)

这就是你所需要的:

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
pi  = np.pi
n = 10
x = np.linspace(-pi,pi,100)
y = (1/(2*pi)) + (1/pi)*(sum(np.cos(i * x) for i in xrange(1, n)))

plt.plot(x,y)
plt.show()

基本上你只有一个列表理解能为你做总结:

sum(np.cos(i * x) for i in xrange(1, n))

答案 1 :(得分:2)

您可以使用列表理解:

n = 10
y = ao + (1/pi) * sum([np.cos((i+1)*x) for i in range(n)])