How to calculate a Fourier series in Numpy?

Mermoz picture Mermoz · Nov 23, 2010 · Viewed 52.5k times · Source

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.

Answer

Mermoz picture Mermoz · Nov 24, 2010

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