import numpy as np
import matplotlib.pyplot as plt
T = 5
h=2
a = 1
numPoints = 101
x = np.linspace(-T/2, T/2,numPoints)
true_fun1 = np.zeros(np.shape(x))
true_fun1 = (h/a)*(x+a)
true_fun1[x<-a] = 0
true_fun1[x>=0] = 0
true_fun2 = np.zeros(np.shape(x))
true_fun2 = (-h/a)*(x-a)
true_fun2[x>a] = 0
true_fun2[x<=0] = 0
true_fun = true_fun1 + true_fun2
true_fun[int((numPoints-1)/2)] = h
plt.plot(x, true_fun)
plt.show()
Fourier_series_2 = np.ones(np.shape(x))*(a*h/T)
for n in np.arange(1,2):
Fourier_series_2+= (2/T)*(2*h/a)*(T/(2*np.pi*n))**2 * (1-np.cos((2*np.pi * a *n)/T))\
* np.cos((2*np.pi*n*x)/T)
Fourier_series_5 = np.ones(np.shape(x))*(a*h/T)
for n in np.arange(1,5):
Fourier_series_5+= (2/T)*(2*h/a)*(T/(2*np.pi*n))**2 * (1-np.cos((2*np.pi * a *n)/T))\
* np.cos((2*np.pi*n*x)/T)
Fourier_series_10 = np.ones(np.shape(x))*(a*h/T)
for n in np.arange(1,10):
Fourier_series_10+= (2/T)*(2*h/a)*(T/(2*np.pi*n))**2 * (1-np.cos((2*np.pi * a *n)/T))\
* np.cos((2*np.pi*n*x)/T)
Fourier_series_100 = np.ones(np.shape(x))*(a*h/T)
for n in np.arange(1,100):
Fourier_series_100+= (2/T)*(2*h/a)*(T/(2*np.pi*n))**2 * (1-np.cos((2*np.pi * a *n)/T))\
* np.cos((2*np.pi*n*x)/T)
ax= plt.figure(facecolor="w", figsize=(6,4))
plt.plot(x, Fourier_series_5, label='first 5 terms')
plt.plot(x, Fourier_series_10, label='first 10 terms')
plt.plot(x, Fourier_series_100, label='first 100 terms')
plt.plot(x, true_fun, 'k-.', alpha=.8, label='original function')
plt.title('Fourier cosine series', fontsize=13)
plt.legend(fontsize=13)
plt.yticks(fontsize=13)
plt.xticks(fontsize=13)
plt.savefig('FourierSeries1.png', dpi = 300)
import numpy as np
import matplotlib.pyplot as plt
M = 1
T=2
numPoints = 101
x = np.linspace(-T, T,numPoints)
true_fun = -M*np.ones(np.shape(x))
true_fun[x<T/2] = M
true_fun[x<=0] = -M
true_fun[x<=-T/2] = M
plt.plot(x, true_fun)
plt.show()
T=2
x = np.linspace(-T, T,numPoints)
Fourier_series_2 = np.zeros(np.shape(x))*(a*h/T)
for n in np.arange(1,2):
Fourier_series_2+= (2*M/np.pi/n) * (1-np.cos(2*np.pi*n/T)) * np.sin(2*np.pi*n*x/T)
Fourier_series_5 = np.zeros(np.shape(x))*(a*h/T)
for n in np.arange(1,5):
Fourier_series_5+= (2*M/np.pi/n) * (1-np.cos(2*np.pi*n/T)) * np.sin(2*np.pi*n*x/T)
Fourier_series_10 = np.zeros(np.shape(x))*(a*h/T)
for n in np.arange(1,10):
Fourier_series_10+= (2*M/np.pi/n) * (1-np.cos(2*np.pi*n/T)) * np.sin(2*np.pi*n*x/T)
Fourier_series_100 = np.zeros(np.shape(x))*(a*h/T)
for n in np.arange(1,100):
Fourier_series_100+= (2*M/np.pi/n) * (1-np.cos(2*np.pi*n/T)) * np.sin(2*np.pi*n*x/T)
ax= plt.figure(facecolor="w", figsize=(6,4))
plt.plot(x, Fourier_series_5, label='first 5 terms')
plt.plot(x, Fourier_series_10, label='first 10 terms')
plt.plot(x, Fourier_series_100, label='first 100 terms')
plt.plot(x, true_fun, 'k-.', alpha=.8, label='original function')
plt.title('Complex Fourier series (sine in this case)', fontsize=13)
plt.legend(fontsize=13)
plt.yticks(fontsize=13)
plt.xticks(fontsize=13)
plt.savefig('FourierSeries1.png', dpi = 300)