← Back to Figures
Figure 2.4:
Function f(x)=\exp \big (-8\big (\frac {x}{\pi }\big )^{2}\big ) and truncated trigonometric Fourier series approximations with K=2,5,10. The approximations with K=5 and K=10 are visually indistinguishable from the exact function.
Code for Figure 2.4
Text of the GNU GPL .
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 import numpy as np
import matplotlib.pyplot as plt
nxs = 1000
x = np . linspace ( - np . pi , np . pi , nxs )
dx = 2 * np . pi / ( nxs - 1 )
nterms = [ 2 , 5 , 10 ]
u = np . zeros (( len ( nterms ), nxs ))
ntermsmax = nterms [ - 1 ]
phi = np . zeros (( ntermsmax + 1 , nxs ))
phi [ 0 , :] = 1 / np . sqrt ( 2 * np . pi )
for m in range ( 1 , ntermsmax ):
phi [ m , :] = 1 / np . sqrt ( np . pi ) * np . cos ( m * x )
flist = np . exp ( - 8 * ( x ** 2 ) / np . pi ** 2 )
for i in range ( len ( nterms )):
for k in range ( nterms [ i ] + 1 ):
ck = np . dot ( flist , phi [ k , :]) * dx
u [ i , :] += ck * phi [ k , :]
plt . plot ( x , flist , '-' , x , u [ 0 , :], '--' , x , u [ 1 , :], ':' , x , u [ 2 , :], '-.' )
plt . legend ([ 'exp(-8x^2/pi^2)' , 'K=2' , 'K=5' , 'K=10' ])
plt . show ( block = False )
table = np . column_stack (( x , flist , u . transpose ()))
np . savetxt ( 'FourierGaussian.dat' , table , fmt = ' %f ' )