import numpy as np
import matplotlib.pyplot as plt
from scipy.special import legendre
nxs = 1000
x = np.linspace(-1, 1, nxs)
dx = 2 / (nxs - 1)
nterms = [2, 5, 10]
u = np.zeros((len(nterms), nxs))
ntermsmax = nterms[-1]
phi = np.zeros((ntermsmax + 1, nxs))
for m in range(ntermsmax + 1):
P = legendre(m)(x)
phi[m, :] = P * np.sqrt((2 * m + 1) / 2)
flist = np.exp(-8 * x**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)', 'n=2', 'n=5', 'n=10'])
plt.show(block=False)
table = np.column_stack( (x, flist, u.T) )
with open("LegendreGaussian.dat", "w") as f:
np.savetxt(f, table, fmt='%f', header="table")