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 4. NUMERICAL QUADRATURE AND DIFFERENTIATION 150<br />

Trapezoidal rule<br />

In [1]: function trap(f::Function,a,b)<br />

(f(a)+f(b))*(b-a)/2<br />

end<br />

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

Let’s verify the calculations of Example 72:<br />

In [2]: trap(x->x^x,0.5,1)<br />

Out[2]: 0.42677669529663687<br />

Simpson’s rule<br />

In [3]: function simpson(f::Function,a,b)<br />

(f(a)+4f((a+b)/2)+f(b))*(b-a)/6<br />

end<br />

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

In [4]: simpson(x->x^x,0.5,1)<br />

Out[4]: 0.4109013813880978<br />

Recall that the degree of accuracy of Simpson’s rule is 3. This means the rule<br />

<strong>in</strong>tegrates polynomials 1,x,x 2 ,x 3 exactly, but not x 4 . Wecanusethisasawayto<br />

verify our code:<br />

In [5]: simpson(x->x,0,1)<br />

Out[5]: 0.5<br />

In [6]: simpson(x->x^2,0,1)<br />

Out[6]: 0.3333333333333333

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

Saved successfully!

Ooh no, something went wrong!