python - Fourier Series in Numpy. Question about Previous Answer -


i'm trying replicate answer given in previous thread: how calculate fourier series in numpy?

import numpy np import matplotlib.pyplot plt import itertools  def func(x):     if x >= 1.0 or x <= -1.0:         return 0     else:         return (abs(x) - 1.0) = 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) in range(1,nh+1)])     return f.sum() y2 = np.array([f(t,10).real t in time]) ax.plot(time, y2) plt.show() 

i'm getting solution that's close right answer, shifted. wasn't sure doing wrong. shifted fourier series

the error seems related riemann sum method (right/middle/left) - indicated regularfry. using middle method gives:

enter image description here

code:

import numpy np import matplotlib.pyplot plt import itertools  def func(x):     if x >= 1.0 or x <= -1.0:         return 0     else:         return (abs(x) - 1.0)  = 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]))  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):     rng = np.arange(.5, nh+.5)     f = np.array([2*cn(i)*np.exp(1j*2*i*np.pi*x/period) in rng])     return f.sum()  y2 = np.array([f(t,10).real t in time])  fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.plot(time, y) ax.plot(time, y2) plt.show() 

as noted sven in another question use of list comprehensions (and imap) instead of arrays , ufuncs quite inefficient (should run performance issues)


Comments