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

end<br />

end<br />

return(a)<br />

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

In [5]: function newton(x::Array,y::Array,z)<br />

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

# degree of the polynomial<br />

a=diff(x,y)<br />

sum=a[1]<br />

pr=1.0<br />

for j <strong>in</strong> 1:(m-1)<br />

pr=pr*(z-x[j])<br />

sum=sum+a[j+1]*pr<br />

end<br />

return sum<br />

end<br />

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

Here is the code that computes the cubic spl<strong>in</strong>e, Newton <strong>in</strong>terpolation, and plot<br />

them.<br />

In [6]: us<strong>in</strong>g LaTeXStr<strong>in</strong>gs<br />

xaxis=-5:1/100:5<br />

f(x)=1/(1+x^2)<br />

runge=f.(xaxis)<br />

xi=collect(-5:1:5)<br />

yi=map(f,xi)<br />

CubicNatural(xi,yi)<br />

naturalspl<strong>in</strong>e=map(z->CubicNaturalEval(z,xi),xaxis)<br />

<strong>in</strong>terp=map(z->newton(xi,yi,z),xaxis) # Interpolat<strong>in</strong>g polynomial<br />

# for the data<br />

plot(xaxis,runge,label=L"1/(1+x^2)")<br />

plot(xaxis,<strong>in</strong>terp,label="Interpolat<strong>in</strong>g poly")<br />

plot(xaxis,naturalspl<strong>in</strong>e,label="Natural cubic spl<strong>in</strong>e")

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

Saved successfully!

Ooh no, something went wrong!