# %pip install seaborn matplotlib
# %pip install scikit-learn plotnine tqdm pandas
# %pip install numpy ## gets installed with scikit-learn
# %pip install tqdm
# %pip install torch
# %pip install torchvision torchmetrics
test
notebook
Install packages for gene46100
import numpy as np
import matplotlib.pyplot as plt
def periodic_u(x_values):
"""
Calculates the periodic function u(x) = x, with period L=1.
This is equivalent to u(x) = x - floor(x) for an array of x values.
Args:
x_values (np.array): Input x values.
Returns:
np.array: Values of the periodic function.
"""
return x_values - np.floor(x_values)
def fourier_series_approx(x_values, n_terms_approx):
"""
Calculates the Fourier series approximation of u(x).
The formula derived is: u_approx(x) = 1/2 - (1/pi) * sum_{n=1}^{N} (sin(2*pi*n*x) / n)
Args:
x_values (np.array): Input x values.
n_terms_approx (int): Number of terms (N) to include in the summation.
Returns:
np.array: Values of the Fourier series approximation.
"""
# Initialize an array of zeros with the same shape as x_values to store the sum
= np.zeros_like(x_values, dtype=float)
series_sum_val
# Sum the series term by term
for n_val in range(1, n_terms_approx + 1):
+= (np.sin(2 * np.pi * n_val * x_values)) / n_val
series_sum_val
# Apply the full formula
= 0.5 - (1 / np.pi) * series_sum_val
approximation return approximation
# --- Parameters for plotting ---
= 100 # Number of terms in the Fourier series approximation
N_TERMS_IN_SERIES = 0 # Minimum x value for plotting
X_PLOT_MIN = 3 # Maximum x value for plotting (to show 3 periods)
X_PLOT_MAX = 1000 # Number of points for generating smooth plot lines
NUM_POINTS_PLOT
# --- Generate x values for plotting ---
# Using linspace to create an array of evenly spaced x values
= np.linspace(X_PLOT_MIN, X_PLOT_MAX, NUM_POINTS_PLOT)
x_plot_values
# --- Calculate y values for the original periodic function ---
= periodic_u(x_plot_values)
y_original_periodic
# --- Calculate y values for the Fourier series approximation ---
= fourier_series_approx(x_plot_values, N_TERMS_IN_SERIES)
y_fourier_approximation
# --- Plotting the results ---
=(14, 8)) # Create a figure with a specified size for better readability
plt.figure(figsize
# Plot the original periodic function
='Original periodic function $u(x) = x - \\lfloor x \\rfloor$', color='dodgerblue', linewidth=2.5)
plt.plot(x_plot_values, y_original_periodic, label
# Plot the Fourier series approximation
=f'Fourier Series Approx. ({N_TERMS_IN_SERIES} terms)', color='red', linestyle='--', linewidth=2)
plt.plot(x_plot_values, y_fourier_approximation, label
# --- Adding plot enhancements ---
f'Original Function vs. Fourier Series Approximation\n($u(x)=x$, period $L=1$, {N_TERMS_IN_SERIES} terms)', fontsize=18)
plt.title('$x$', fontsize=16)
plt.xlabel('$u(x)$', fontsize=16)
plt.ylabel(=12, loc='upper right')
plt.legend(fontsizeTrue, linestyle=':', alpha=0.6) # Add a grid for easier value reading
plt.grid(-0.25, 1.25) # Set y-axis limits to focus on the function's range
plt.ylim(0, color='black', linewidth=0.75) # Add a horizontal line at y=0
plt.axhline(0, color='black', linewidth=0.75) # Add a vertical line at x=0
plt.axvline(
# Add text annotations for clarity if needed, e.g., pointing out Gibbs phenomenon
# plt.annotate('Gibbs Phenomenon', xy=(1, 0.9), xytext=(1.2, 0.7),
# arrowprops=dict(facecolor='black', shrink=0.05), fontsize=10)
# Display the plot
plt.show()