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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 5. APPROXIMATION THEORY 209<br />

In [5]: us<strong>in</strong>g Base.MathConstants<br />

The <strong>in</strong>ner product, 〈 ∫<br />

e x , 3 2 x2 − 2〉 1 1<br />

=<br />

−1 ex ( 3 2 x2 − 1 )dx is computed as<br />

2<br />

In [6]: gauss(x->((3/2)*x^2-1/2)*e^x)<br />

Out[6]: 0.1431256282441218<br />

Nowthatwehaveacodeleg(x,n) that generates the Legendre polynomials, we<br />

can do the above computation <strong>with</strong>out explicitly specify<strong>in</strong>g the Legendre polynomial.<br />

For example, s<strong>in</strong>ce 3 2 x2 − 1 = L 2 2, we can apply the gauss function directly to L 2 (x)e x :<br />

In [7]: gauss(x->leg(x,2)*e^x)<br />

Out[7]: 0.14312562824412176<br />

〈f,L j 〉<br />

α j<br />

The follow<strong>in</strong>g function polyLegCoeff(f::Function,n) computes the coefficients<br />

〈f,L j 〉<br />

α j<br />

L j (x),j =0, 1, ..., n, for any<br />

of the least squares polynomial P n (x) = ∑ n<br />

j=0<br />

f and n, where L j are the Legendre polynomials. Note that the <strong>in</strong>dices are shifted <strong>in</strong><br />

thecodesothatj starts at 1 not 0. The coefficients are stored <strong>in</strong> the global array A.<br />

In [8]: function polyLegCoeff(f::Function,n)<br />

global A=Array{Float64}(undef,n+1)<br />

for j <strong>in</strong> 1:n+1<br />

A[j]=gauss(x->leg(x,(j-1))*f(x))*(2(j-1)+1)/2<br />

end<br />

end<br />

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

Once the coefficients are computed, evaluat<strong>in</strong>g the polynomial can be done efficiently<br />

by call<strong>in</strong>g the array A. The next function polyLeg(x,n) evaluates the least<br />

squares polynomial P n (x) = ∑ n 〈f,L j 〉<br />

j=0 α j<br />

L j (x),j =0, 1, ..., n, where the coefficients 〈f,L j〉<br />

α j<br />

are obta<strong>in</strong>ed from the array A.<br />

In [9]: function polyLeg(x,n)<br />

sum=0.;<br />

for j <strong>in</strong> 1:n+1

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

Saved successfully!

Ooh no, something went wrong!