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 3. INTERPOLATION 105<br />

In the first iteration (for loop, j =2), a 1 and a 2 are updated:<br />

a 1 := a 1 − a 0<br />

x 1 − x 0<br />

= y 1 − y 0<br />

x 1 − x 0<br />

= f[x 0 ,x 1 ],a 2 := a 2 − a 1<br />

x 2 − x 1<br />

= y 2 − y 1<br />

x 2 − x 1<br />

.<br />

In the last iteration (for loop, j =3), only a 2 is updated:<br />

a 2 := a 2 − a 1<br />

x 2 − x 0<br />

=<br />

y 2 −y 1<br />

x 2 −x 1<br />

− y 1−y 0<br />

x 1 −x 0<br />

x 2 − x 0<br />

= f[x 0 ,x 1 ,x 2 ].<br />

The f<strong>in</strong>al array a is<br />

a =(y 0 ,f[x 0 ,x 1 ],f[x 0 ,x 1 ,x 2 ])<br />

conta<strong>in</strong><strong>in</strong>g the divided differences needed to construct the Newton’s form of the polynomial.<br />

Here is the <strong>Julia</strong> function diff which computes the divided differences. The code uses a<br />

function we have not used before: reverse(collect(j:m)). An example illustrates what it<br />

does the best:<br />

In [1]: reverse(collect(2:5))<br />

Out[1]: 4-element Array{Int64,1}:<br />

5<br />

4<br />

3<br />

2<br />

In the code diff the <strong>in</strong>puts are the x and y-coord<strong>in</strong>ates of the data. The number<strong>in</strong>g<br />

of the <strong>in</strong>dices starts at 1, not 0.<br />

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

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

#the degree of the polynomial is m-1<br />

a=Array{Float64}(undef,m)<br />

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

a[i]=y[i]<br />

end<br />

for j <strong>in</strong> 2:m<br />

for i <strong>in</strong> reverse(collect(j:m))<br />

a[i]=(a[i]-a[i-1])/(x[i]-x[i-(j-1)])

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

Saved successfully!

Ooh no, something went wrong!