fourier series coefficients in python

The steps to find Fourier series coefficients in python are:

  1. Define the function to be analyzed.
  2. Create time and frequency arrays.
  3. Use the NumPy library to compute the Fourier coefficients.
  4. Use the coefficients to generate the Fourier series using the inverse Fourier transform (IFFT).
  5. Plot the original function and the Fourier series approximation.

Here's an example code snippet:

main.py
import numpy as np
import math
import matplotlib.pyplot as plt

# Define the function to be analyzed (a square wave)
def square_wave(x):
    y = np.zeros(len(x))
    for i in range(len(x)):
        if np.sin(x[i]) >= 0:
            y[i] = 1
        else:
            y[i] = -1
    return y

# Create time and frequency arrays
t = np.linspace(0, 2*np.pi, 1000)
dt = t[1] - t[0]
f = np.linspace(-1/(2*dt), 1/(2*dt), len(t))

# Compute the Fourier coefficients
y = square_wave(t)
Y = np.fft.fftshift(np.fft.fft(y))/len(y)

# Generate the Fourier series
n = len(y)
y_ift = np.zeros_like(y)
for i in range(n):
    y_ift += Y[i]*np.exp(2*math.pi*1j*i*np.arange(n)/n)

# Plot the original function and the Fourier series approximation
plt.plot(t, y, label='original function')
plt.plot(t, y_ift.real, label='Fourier series')
plt.legend()
plt.show()
842 chars
35 lines

In this example, we define a square wave function and create a time array t and corresponding frequency array f. We compute the Fourier coefficients using the NumPy library's fft function and the fftshift function to shift the zero-frequency component to the center of the spectrum. We then use the coefficients to generate the Fourier series using the inverse Fourier transform, and finally, we plot the original function and the Fourier series approximation.

gistlibby LogSnag