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 213<br />

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

The <strong>in</strong>tegrals <strong>in</strong> Example 94 were computed us<strong>in</strong>g the composite Simpson rule <strong>with</strong><br />

n =20. For example, the second <strong>in</strong>tegral 〈e x ,T 1 〉 = ∫ π<br />

0 ecos θ cos θdθ is computed as:<br />

In [14]: compsimpson(x->exp(cos(x))*cos(x),0,pi,20)<br />

Out[14]: 1.7754996892121808<br />

Next we write two functions, polyChebCoeff(f::Function,n) and<br />

polyCheb(x,n). The first function computes the coefficients 〈f,T j〉<br />

of the least<br />

〈f,T j 〉<br />

α j<br />

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

j=0<br />

T j (x),j =0, 1, ..., n, for any f and n, where T j<br />

are the Chebyshev polynomials. Note that the <strong>in</strong>dices are shifted <strong>in</strong> the code so that<br />

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

The <strong>in</strong>tegral 〈f,T j 〉 is transformed to the <strong>in</strong>tegral ∫ π<br />

f(cos θ)cos(jθ)dθ, similar to<br />

0<br />

the derivation <strong>in</strong> Example 94, and then the transformed <strong>in</strong>tegral is computed us<strong>in</strong>g the<br />

composite Simpson’s rule by polyChebCoeff.<br />

In [15]: function polyChebCoeff(f::Function,n)<br />

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

A[1]=compsimpson(x->f(cos(x)),0,pi,20)/pi<br />

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

A[j]=compsimpson(x->f(cos(x))*cos((j-1)*x),0,pi,20)*2/pi<br />

end<br />

end<br />

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

In [16]: function polyCheb(x,n)<br />

sum=0.;<br />

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

sum=sum+A[j]*cheb(x,(j-1))<br />

end<br />

return(sum)<br />

end<br />

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

α j

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

Saved successfully!

Ooh no, something went wrong!