% legendre_expansion.m % Legendre EXpansion over [-1,1] % P0 = 1; P1 = x; P2 = (3/2)*x^2-(1/2) % mu_j = (Pj, Pj) = 2/(2j+1) = 2, 2/3, 2/5 % p(x) = sum_{j=0}^2 a_j*P_j % a_j = (f,P_j)/(P_j.P_j) = (f, P_j)/mu_j
function main(n);
f = @(x) exp(x); xx = linspace(-1,1,1000); % Graphical points fx = f(xx); Px = zeros(1,length(xx));
for k=0:n pk=Legen_poly(k); g = @(x) f(x).*polyval(pk,x); ak = quad(g,-1,1)/(2/(2*k+1)); Px = Px + ak*polyval(pk,xx); end
fprintf('Maximum Error of |f(x)-Pn(x)| = %12.4e \n', max(abs(fx-Px))) plot(xx,fx,xx,Px); title(['Legendre Expansion of degree ', num2str(n)] ) legend('f(x)', 'p_n(x)')
%%%%%%%% Legendre polynomial of degree n %%%%%%%% function pn = Legen_poly(n); pbb = [1]; if n==0, pn=pbb; return; end pb = [1 0]; if n==1, pn=pb; return; end for i=2:n; pn = ( (2*i-1)*[pb,0] - (i-1)*[0, 0, pbb] )/i; pbb = pb; pb=pn; end
|
|