06.09.2021 Views

First Semester in Numerical Analysis with Julia, 2020a

First Semester in Numerical Analysis with Julia, 2020a

First Semester in Numerical Analysis with Julia, 2020a

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 5. APPROXIMATION THEORY 207<br />

Therefore<br />

P 3 (x) = 3.977 + 3.55<br />

π π x + 0.853<br />

π (2x2 − 1) + 0.1393 (4x 3 − 3x)<br />

π<br />

=0.1774x 3 +0.5430x 2 +0.9970x +0.9944.<br />

<strong>Julia</strong> code for orthogonal polynomials<br />

Comput<strong>in</strong>g Legendre polynomials<br />

Legendre polynomials satisfy the follow<strong>in</strong>g recursion:<br />

L n+1 (x) =<br />

2n +1<br />

n +1 xL n(x) −<br />

n<br />

n +1 L n−1(x)<br />

for n =1, 2,..., <strong>with</strong> L 0 (x) =1,andL 1 (x) =x.<br />

The <strong>Julia</strong> code implements this recursion, <strong>with</strong> a little modification: the <strong>in</strong>dex n +1is<br />

shifted down to n, so the modified recursion is: L n (x) = 2n−1xL<br />

n n−1(x) − n−1L<br />

n n−2(x), for<br />

n =2, 3,....<br />

In [1]: us<strong>in</strong>g PyPlot<br />

us<strong>in</strong>g LaTeXStr<strong>in</strong>gs<br />

In [2]: function leg(x,n)<br />

n==0 && return 1<br />

n==1 && return x<br />

((2*n-1)/n)*x*leg(x,n-1)-((n-1)/n)*leg(x,n-2)<br />

end<br />

Out[2]: leg (generic function <strong>with</strong> 1 method)<br />

Here is a plot of the first five Legendre polynomials:<br />

In [3]: xaxis=-1:1/100:1<br />

legzero=map(x->leg(x,0),xaxis)<br />

legone=map(x->leg(x,1),xaxis)<br />

legtwo=map(x->leg(x,2),xaxis)<br />

legthree=map(x->leg(x,3),xaxis)<br />

legfour=map(x->leg(x,4),xaxis)<br />

plot(xaxis,legzero,label=L"L_0(x)")

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!