汪群超 Chun-Chao Wang

Dept. of Statistics, National Taipei University, Taiwan

Python in Learning

Example: Draw the function f(x) = \frac{4}{\pi}(\sin x + \frac{\sin 3x}{3} + \frac{\sin 5x}{5} + \frac{\sin 7x}{7} + \cdots)

import numpy as np
import matplotlib.pyplot as plt

n = 10 # n terms as n goes to infinity
f = np.arange(n)
x = np.linspace(-3*np.pi, 3*np.pi, 200)
y = np.zeros(len(x)) # initial setting
plt.axis([-3*np.pi, 3*np.pi, -3, 3]) # fix axis range
plt.grid(True)
for i in f:  
    k = 2 * i + 1
    y = y + np.sin(k * x) / k
    plt.plot(x, y*4/np.pi, color='b')
    # plt.pause(0.5) # not work for jupyter
plt.title('Squared wave')
plt.show()