I'm trying to replicate an answer given in a previous thread: How to calculate a Fourier series in Numpy?
import numpy as np
import matplotlib.pyplot as plt
import itertools
def func(x):
if x >= 1.0 or x <= -1.0:
return 0
else:
return (abs(x) - 1.0)
a = 1.0
b = -1.0
N = 128.
time = np.linspace( a, b, N )
y = (np.fromiter(itertools.imap(func, time),
dtype=time.dtype, count=time.shape[0]))
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.plot(time,y)
period = 2.
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,10).real for t in time])
ax.plot(time, y2)
plt.show()
I'm getting a solution that's close to the right answer, but shifted. I wasn't sure what I am doing wrong.