Created
May 17, 2025 19:44
-
-
Save tallpeak/7a854677ebef3577327f6aa00c221be7 to your computer and use it in GitHub Desktop.
a plot of a sum of sine waves, emulating the reconstruction from a fourier transfer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import matplotlib.pyplot as plt | |
# Parameters | |
PI = np.pi | |
N_TERMS = 10 # Number of sine terms | |
NUM_POINTS = 1000 # Number of x values | |
# Function to compute Fourier sine coefficient a_n for x^3 | |
def compute_coefficient(n): | |
x = np.linspace(0, PI, NUM_POINTS) | |
y = x**3 * np.sin(n * x) | |
h = x[1] - x[0] | |
integral = h * (y[0]/2 + np.sum(y[1:-1]) + y[-1]/2) | |
return (2 / PI) * integral | |
# Approximate x^3 using sine series | |
def approximate_x3(x, coeffs): | |
sum = np.zeros_like(x) | |
for n in range(1, N_TERMS + 1): | |
sum += coeffs[n - 1] * np.sin(n * x) | |
return sum | |
# Compute all coefficients | |
coeffs = [compute_coefficient(n) for n in range(1, N_TERMS + 1)] | |
# Evaluate the actual and approximated function | |
x_vals = np.linspace(-PI, PI, NUM_POINTS) | |
actual_vals = x_vals**3 | |
approx_vals = approximate_x3(x_vals, coeffs) | |
# Plot | |
plt.figure(figsize=(10, 6)) | |
plt.plot(x_vals, actual_vals, label='Actual $x^3$', linewidth=2) | |
plt.plot(x_vals, approx_vals, label=f'Sine Approx. ({N_TERMS} terms)', linestyle='--') | |
plt.title('Approximation of $x^3$ using Sine Functions') | |
plt.xlabel('x') | |
plt.ylabel('y') | |
plt.grid(True) | |
plt.legend() | |
plt.tight_layout() | |
plt.show() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment