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

1, 2, ..., n +1given by<br />

A kj =<br />

m∑<br />

i=1<br />

x k+j−2<br />

i .<br />

The equation Aa = b has a unique solution if the x i are dist<strong>in</strong>ct, and n ≤ m − 1. Solv<strong>in</strong>g<br />

this equation by comput<strong>in</strong>g the <strong>in</strong>verse matrix A −1 is not advisable, s<strong>in</strong>ce there could be<br />

significant roundoff error. Next, we will write a <strong>Julia</strong> code for least squares approximation,<br />

and use the <strong>Julia</strong> function A\b to solve the matrix equation Aa = b for a. The\ operation<br />

<strong>in</strong> <strong>Julia</strong> uses numerically optimized matrix factorizations to solve the matrix equation. More<br />

details on this topic can be found <strong>in</strong> Heath [10] (Chapter 3).<br />

<strong>Julia</strong> code for least squares approximation<br />

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

The function leastsqfit takes the x and y-coord<strong>in</strong>ates of the data, and the degree<br />

of the polynomial we want to use, n, as <strong>in</strong>puts. It solves the matrix Equation (5.2).<br />

In [2]: function leastsqfit(x::Array,y::Array,n)<br />

m=length(x) # number of data po<strong>in</strong>ts<br />

d=n+1 # number of coefficients to determ<strong>in</strong>e<br />

A=zeros(d,d)<br />

b=zeros(d,1)<br />

# the l<strong>in</strong>ear system we want to solve is Ax=b<br />

p=Array{Float64}(undef,2*n+1)<br />

for k <strong>in</strong> 1:d<br />

sum=0<br />

for i <strong>in</strong> 1:m<br />

sum=sum+y[i]*x[i]^(k-1)<br />

end<br />

b[k]=sum<br />

end<br />

# p[i] below is the sum of the (i-1)th power of the x<br />

# coord<strong>in</strong>ates<br />

p[1]=m<br />

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

sum=0

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

Saved successfully!

Ooh no, something went wrong!