SS22 Scientific Coding with Julia

Not the most efficient way of computing π\pi

As we very well know, there are a lot of ways to compute π\pi. There is even a blog entry in the Julia blog for that. Nevertheless, we decided for a different method (that is part of the introductory courses on JuliaAcademy).

A circle with radius rr has an area of

Acircle=πr2A_{circle} = \pi r^2

and the square that encases it

Asquare=4r2.A_{square} = 4 r^2.

The ratio between the area of the circle and the area of the square is

AcircleAsquare=πr24r2=π4 \frac{A_{circle}}{A_{square}} = \frac{\pi r^2}{4 r^2} = \frac{\pi}{4}

and therefore we can define π\pi as

π=4AcircleAsquare. \pi = 4\frac{A_{circle}}{A_{square}}.

The same is true if we just take the first quadrant, so 14\frac14 of the square as well as the circle. This simplification will make the code more compact and faster.

The above formula suggests that we can compute π\pi by a Monte Carlo Method. Actually this example is also included in the Wiki article and it comes with this nice gif.

 Simulation of the Monte Carlo Method for computing π.
Simulation of the Monte Carlo Method for computing π. Original source:

https://commons.wikimedia.org/wiki/File:Pi_30K.gif

The algorithm therefore becomes:

  1. For a given number NN of uniformly scattered points in the quadrant determine if these points are in the circle (distance less than 1) or not. We call the number of points in the circle MM.

  2. Estimate π\pi by computing

π4MN. \pi \approx 4 \frac{M}{N}.
Implement the above described algorithm to compute π\pi.

  1. Define a function that determines MM for a given integer NN.

  2. Define a function that estimates π\pi for a given function ff and integer NN.

  3. Test your code with different values for NN.

Help: The function rand() will give you a uniformly scattered point in the interval [0,1][0,1].

Solution

function in_unit_circle(N::Integer)
    M = 0
    
    for i in 1:N
        if (rand()^2 + rand()^2) < 1
            M += 1
        end
    end

    return M
end

function estimate_pi(f::Function, N::Integer)
    return 4 * f(N) / N
end

function get_accuracy(f::Function, N::Integer)
    return abs(
        estimate_pi(f, N) - pi
        )
end

N = 2^30
get_accuracy(in_unit_circle, N)

4.897092516031876e-5
CC BY-SA 4.0 - Gregor Ehrensperger, Peter Kandolf, Jonas Kusch. Last modified: September 09, 2022. Website built with Franklin.jl and the Julia programming language.