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 2. SOLUTIONS OF EQUATIONS: ROOT-FINDING 84<br />

In [5]: fixedpt(x->x-(x^2-2)/4,-5.,10^(-5),15)<br />

Did not converge. The last estimate is p=-Inf.<br />

Let’s verify the l<strong>in</strong>ear convergence of the fixed-po<strong>in</strong>t iteration numerically <strong>in</strong> this example.<br />

We write another version of the fixed-po<strong>in</strong>t code, fixedpt2, and we compute pn−√ 2<br />

p n−1 − √ for each<br />

2<br />

n. The code uses some functions we have not seen before:<br />

• global list def<strong>in</strong>es the variable list as a global variable, which allows us to access list<br />

outside the function def<strong>in</strong>ition, where we plot it;<br />

• Float64[ ] creates an empty array of dimension 1, <strong>with</strong> a float type;<br />

• append!(list,x) appends x to the list.<br />

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

In [7]: function fixedpt2(g::Function,pzero,eps,N)<br />

n=1<br />

global list<br />

list=Float64[]<br />

error=1.<br />

while n10^-5.<br />

pone=g(pzero)<br />

error=abs(pone-pzero)<br />

append!(list,(pone-2^0.5)/(pzero-2^0.5))<br />

pzero=pone<br />

n=n+1<br />

end<br />

return(list)<br />

end<br />

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

In [8]: fixedpt2(x->x-(x^2-2)/4,1.5,10^(-7),15)<br />

Out[8]: 9-element Array{Float64,1}:<br />

0.27144660940672544

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

Saved successfully!

Ooh no, something went wrong!