<p>如果您是编程新手,这可能与您现在所做的有点不同,但是我基本上将函数拆分,以解释每个组件的功能,更重要的是,使用了numpy的内置函数,它将被证明比嵌套循环更有效,尤其是当您的数据变得更大时</p>
<p>为了理解函数<code>f</code>发生了什么,请在Python中查找(列表)理解,但它基本上是一个用单行表示的<code>for</code>循环</p>
<pre><code>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()
</code></pre>
<p><a href="https://i.stack.imgur.com/80PJG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/80PJG.png" alt="enter image description here"/></a></p>