Векторизованная версия вашего кода:
import numpy as np
import matplotlib.pyplot as plt
from optparse import OptionParser
def func(x):
return np.where(np.abs(x) >= 1, 0., np.abs(x) - 1.0)
def cn(x, y, n, period):
c = y * np.exp(-1j * 2. * np.pi * n * x / period)
return c.sum()/c.size
def f(x, y, Nh, period):
rng = np.arange(.5, Nh+.5)
coeffs = np.array([cn(x,y,i,period) for i in rng])
f = np.array([2. * coeffs[i] * np.exp(1j*2*i*np.pi*x/period) for i in rng])
return f.sum(axis=0)
if __name__=='__main__':
Version = '0.1'
usage = "usage: %prog [options]"
parser = OptionParser(usage = usage,version="%prog "+Version)
parser.add_option("-a", dest='a', type='float', default=1., help="initial time")
parser.add_option("-b", dest='b', type='float', default=-1., help="end time")
parser.add_option("-N", "--Nt", dest='N', type='int', default=128, help="number of time steps")
parser.add_option("-p", "--period", dest='period', type='float', default=2., help="period [time span]")
parser.add_option("--Nh", dest='Nh', type='int', default=10, help="number of fourier series terms")
(options, args) = parser.parse_args()
for key,value in options.__dict__.iteritems():
exec key + ' = ' + repr(value)
time = np.linspace( a, b, N )
y = func(time)
period = np.abs(a-b)
y2 = f(time,y,Nh,period).real
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.plot(time, y)
ax.plot(time, y2)
plt.show()
Учитывая, что код был сохранен с именем "fourier_series.py", вы можете попробовать:
python fourier_series.py -N 512 --Nh 128
в обычном терминале или:
% run fourier_series.py -N 512 --Nh 128
в консоли ipython