如果您是编程新手,这可能看起来与您现在正在做的有点不同,但是我基本上已经将功能分开来解释每个组件的作用,更重要的是,使用了 numpy 的内置函数,这将被证明是比嵌套循环更有效,尤其是当您的数据变大时。
要了解函数发生了什么f
,请在 Python 中查找(列表)推导,但它基本上是一个for
用单行表示的循环。
In [24]: import numpy as np
...: import matplotlib.pyplot as plt
In [25]: def summand(n, x):
...: """ Return an array of `x`'s size for a given value of `n`.
...: Each element of the array is a value of the function computed
...: at a value in `x` with the given `n`.
...: """
...: return (2 / (n * np.pi)) * (np.cos(n * np.pi / 2) - 1) * np.sin(n * x / 2)
...:
In [26]: def f(x, N=5):
...: """ Return the sum of the summands computed for
...: values of `n` ranging from 1 to N+1 with a given array `x`
...: """
...: return sum(summand(n, x) for n in range(1, N+1))
...:
In [27]: x = np.linspace(-2*np.pi, 6*np.pi, 500)
In [28]: plt.plot(x, f(x))
Out[28]: [<matplotlib.lines.Line2D at 0x23e60b52a00>]
In [29]: plt.show()