Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate a Fourier series in Numpy?

Tags:

python

numpy

fft

I have a periodic function of period T and would like to know how to obtain the list of the Fourier coefficients. I tried using fft module from numpy but it seems more dedicated to Fourier transforms than series. Maybe it a lack of mathematical knowledge, but I can't see how to calculate the Fourier coefficients from fft.

Help and/or examples appreciated.

like image 844
Mermoz Avatar asked Nov 23 '10 16:11

Mermoz


People also ask

How is Fourier series calculated?

So this is what we do: Take our target function, multiply it by sine (or cosine) and integrate (find the area) Do that for n=0, n=1, etc to calculate each coefficient. And after we calculate all coefficients, we put them into the series formula above.

How do you find the Fourier series of a coefficient in Python?

The coefficients are returned as a python list: [a0/2,An,Bn]. a0/2 is the first Fourier coefficient and is a scalar. An and Bn are numpy 1d arrays of size n, which store the coefficients of cosine and sine terms respectively. To calculate these coefficients I perform integration using the script.


1 Answers

In the end, the most simple thing (calculating the coefficient with a riemann sum) was the most portable/efficient/robust way to solve my problem:

import numpy as np def cn(n):    c = y*np.exp(-1j*2*n*np.pi*time/period)    return c.sum()/c.size  def f(x, Nh):    f = np.array([2*cn(i)*np.exp(1j*2*i*np.pi*x/period) for i in range(1,Nh+1)])    return f.sum()  y2 = np.array([f(t,50).real for t in time])  plot(time, y) plot(time, y2) 

gives me: alt text

like image 151
Mermoz Avatar answered Sep 21 '22 22:09

Mermoz