Files
public-blog/content/posts/hybrid-post.mdx

62 lines
1.8 KiB
Plaintext

---
title: "Fourier Analysis: From Math to Code"
date: "2025-03-10"
excerpt: "Bridging the gap between Fourier's mathematical theory and practical implementation."
---
Fourier analysis reveals a profound truth: any periodic function can be decomposed into a sum of simple sine and cosine waves.
## The Math
The Fourier series of a function $f(x)$ with period $2\pi$ is:
$$f(x) = \frac{a_0}{2} + \sum_{n=1}^{\infty} \left( a_n \cos(nx) + b_n \sin(nx) \right)$$
where:
$$a_n = \frac{1}{\pi} \int_{-\pi}^{\pi} f(x)\cos(nx)\,dx$$
$$b_n = \frac{1}{\pi} \int_{-\pi}^{\pi} f(x)\sin(nx)\,dx$$
## Python Implementation
Let's approximate a square wave using the first few terms:
```python
import numpy as np
import matplotlib.pyplot as plt
def fourier_square_wave(x, n_terms):
"""Approximate a square wave using Fourier series."""
result = np.zeros_like(x)
for n in range(1, n_terms + 1, 2): # odd harmonics only
result += (4 / (n * np.pi)) * np.sin(n * x)
return result
x = np.linspace(-np.pi, np.pi, 1000)
plt.figure(figsize=(10, 6))
plt.plot(x, np.where(x >= 0, 1, -1), 'k--', label='Square wave')
for terms in [1, 3, 7, 15]:
plt.plot(x, fourier_square_wave(x, terms), label=f'{terms} terms')
plt.legend()
plt.title('Fourier Series Approximation of a Square Wave')
plt.grid(True, alpha=0.3)
plt.savefig('fourier.png', dpi=150)
```
## Understanding Convergence
The Gibbs phenomenon shows that near discontinuities, the approximation overshoots by approximately:
$$9\%$$
This is mathematically expressed as:
$$\lim_{N \to \infty} \text{overshoot} \approx 1.08949 \times \text{jump}$$
## Conclusion
The connection between the elegant mathematics and practical code demonstrates how theory informs implementation. Fourier analysis is the foundation of signal processing, image compression, and countless other applications.