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

be 2 360 , which is about 10 100 , a number too large. In very large dimensions, the only general<br />

method for numerical <strong>in</strong>tegration is the Monte Carlo method. In Monte Carlo, we generate<br />

pseudorandom numbers from the doma<strong>in</strong>, and evaluate the function average at those po<strong>in</strong>ts.<br />

In other words,<br />

∫<br />

f(x)dx ≈ 1<br />

R n<br />

n∑<br />

f(x i )<br />

where x i are pseudorandom vectors uniformly distributed <strong>in</strong> R. For the two-dimensional<br />

<strong>in</strong>tegral we discussed before, the Monte Carlo estimate is<br />

i=1<br />

∫ b ∫ d<br />

a c<br />

f(x, y)dydx ≈<br />

(b − a)(d − c)<br />

n<br />

n∑<br />

f(a +(b − a)x i ,c+(d − c)y i ) (4.8)<br />

i=1<br />

where x i ,y i are pseudorandom numbers from (0, 1). In <strong>Julia</strong>, the function rand() generates<br />

a pseudorandom number from the uniform distribution between 0 and 1. The follow<strong>in</strong>g code<br />

takes the endpo<strong>in</strong>ts of the <strong>in</strong>tervals a, b, c, d, and the number of nodes n (which is called the<br />

sample size <strong>in</strong> the Monte Carlo literature) as <strong>in</strong>puts, and returns the estimate for the <strong>in</strong>tegral<br />

us<strong>in</strong>g Equation (4.8).<br />

In [1]: function mc(f::Function,a,b,c,d,n)<br />

sum=0.<br />

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

sum=sum+f(a+(b-a)*rand(),c+(d-c)*rand())*(b-a)*(d-c)<br />

end<br />

return sum/n<br />

end<br />

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

Now we use Monte Carlo to estimate the <strong>in</strong>tegral ∫ 1<br />

0<br />

In [2]: mc((x,y)->(pi^2/4)*s<strong>in</strong>(pi*x)*s<strong>in</strong>(pi*y),0,1,0,1,500)<br />

Out[2]: 0.9441778334708931<br />

∫ 1<br />

( π s<strong>in</strong> πx)( π<br />

s<strong>in</strong> πy) dydx:<br />

0 2 2<br />

With n = 500, we obta<strong>in</strong> a Monte Carlo estimate of 0.944178. An advantage of the Monte<br />

Carlo method is its simplicity: the above code can be easily generalized to higher dimensions.<br />

A disadvantage of Monte Carlo is its slow rate of convergence, which is O(1/ √ n). Figure<br />

(4.3) displays 500 pseudorandom vectors from the unit square.

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

Saved successfully!

Ooh no, something went wrong!