import numpy as np
import matplotlib.pyplot as plt
N = 10
A = np.zeros((N, N))
b = np.zeros((N, 1))
for i in range(N-2):
for j in range(N):
A[i, j] = 2. / (2 * j + 1) * (i == j)
for k in range(j+1):
if (j-k) % 2 == 0:
A[i, j] += 4 * (j - k) * (j + k + 1) * (i == k)
for j in range(N):
A[N-2, j] = (-1)**j
A[N-1, j] = 1
for i in range(N-2):
b[i] = -(i == 0) - 1 / 3 * (i == 1)
b[N-2] = 0
b[N-1] = 0
c = np.linalg.solve(A, b)
nxs = 1000
x = np.linspace(-1, 1, nxs)
soln = np.zeros(nxs)
phi = np.zeros((N, nxs))
for m in range(N):
P = np.polynomial.Legendre.basis(m)
phi[m, :] = P(x)
for j in range(N):
for i in range(nxs):
soln[i] += c[j] * phi[j, i]
Nex = 100
hex = 1 / (Nex + 1)
xex = np.linspace(0, 1, Nex+2)
uex = -xex + np.sin(xex) / np.sin(1)
plt.figure()
plt.plot((x + 1) / 2, soln, label='Numerical Solution')
plt.plot(xex, uex, 'r-', label='Exact Solution')
plt.legend()
plt.title('Numerical and Exact Solution')
ind = np.arange(1, N+1)
plt.figure()
plt.semilogy(ind, abs(c), 'o')
plt.title('Semilog Plot of Coefficients')
plt.show(block=False)
t = np.column_stack((ind, abs(c)))
with open("LegendreGalerkin1.dat", "w") as f:
np.savetxt(f, t, fmt='%e', header="Legendre coefficients")