from resources306 import * # for expressionplot
x = sp.symbols('x')
# choose the solution in advance
y = sp.sin(sp.pi*x)*sp.exp(x) # choose anything that satisfies y(0)=0, y(1)=0
expressionplot(y,x,0,1)
# Now choose a differential differential operator
def L(y):
return sp.simplify(sp.diff(y,x,x) + 2*x*sp.diff(y,x) + 5*sp.exp(x)*y)
# and then figure our what f has to be in order for y to be the solution
f = L(y)
f
# basis of dimension 1
phi = x*(x-1)
a1_val = -6 # Pranav's suggestion
expressionplot( a1_val*phi, x, 0, 1,label=f'{a1_val} $\phi$')
expressionplot( y,x,0,1,label='solution y')
plt.legend();
# compute the residual
a1 = sp.symbols('a1')
u = a1*phi
u
rho = L(u)-f # the residual
rho
# need rho to be orthogonal to each phi (of which there's only one here)
# obj = <rho,phi>
obj = sp.simplify(sp.integrate( rho*phi, (x,0,1)))
obj # want this to be zero
a1_optimal = sp.solve(obj,a1)[0]
display(a1_optimal)
float(a1_optimal)
a1_val = float(a1_optimal)
expressionplot( a1_val*phi, x, 0, 1,label=f'{a1_val} $\phi$')
expressionplot( y,x,0,1,label='solution y')
plt.title('Galerkin approximation (blue)')
plt.legend();
expressionplot( rho.subs({a1:a1_optimal})*phi, x, 0,1)
plt.axhline(0,color='k',alpha=0.5)
plt.title('rho phi');
and in fact
sp.integrate( rho.subs({a1:a1_optimal})*phi, (x,0,1) )
That the Galerkin approximation looks worse than Pranav's choice ($a_1=-6$) highlights the observation that the Galerkin approximation does not minimize $||e||^2 = \int_0^1 e^2$.