import numpy as np
import matplotlib.pyplot as plt
blue = "#3399FF"
white = "#FAF9F6"
theta_range = np.linspace(-5 * np.pi, 5 * np.pi, 400)
def f(theta):
theta_wrapped = ((theta + np.pi) % (2 * np.pi)) - np.pi
y = theta_wrapped.copy()
# Insert NaN at discontinuities
jumps = np.abs(np.diff(y)) > np.pi
y[1:][jumps] = np.nan
return y
def f_n(k, theta):
return (-1) ** (k + 1) / k * np.sin(k * theta)
def f_approx(theta, n):
return 2 * sum(f_n(k, theta) for k in range(1, n + 1))
fig, axes = plt.subplots(nrows=3, ncols=2, sharex=True, sharey=True)
fig.set_facecolor(white)
axes[0, 0].plot(theta_range, f(theta_range), color=blue)
axes[0, 0].set_title(r"$f(\theta) = \theta$ extended periodically")
n = 1
axes[0, 1].plot(theta_range, f_approx(theta_range, n), color=blue)
axes[0, 1].set_title(r"$S_1(\theta)$")
n = 2
axes[1, 0].plot(theta_range, f_approx(theta_range, n), color=blue)
axes[1, 0].set_title(r"$S_2(\theta)$")
n = 5
axes[1, 1].plot(theta_range, f_approx(theta_range, n), color=blue)
axes[1, 1].set_title(r"$S_5(\theta)$")
n = 10
axes[2, 0].plot(theta_range, f_approx(theta_range, n), color=blue)
axes[2, 0].set_title(r"$S_{10}(\theta)$")
n = 20
axes[2, 1].plot(theta_range, f_approx(theta_range, n), color=blue)
axes[2, 1].set_title(r"$S_{20}(\theta)$")
for ax in axes.flatten():
ax.set_facecolor(white)
plt.tight_layout()
plt.show()