home

Scientific Computing (Psychology 9040a)

Fall, 2021

Estimate \(\pi\) by throwing darts: sample solution


Here is a sample solution:

function p = estimate_pi(n)
    r = 1;
    inside = 0;
    for i=1:n
        x = rand();
        y = rand();
        if sqrt(x^2 + y^2) <= 1
            inside = inside + 1;
        end
    end
    p = (4*(inside/n));
end

and code to call our function:

estimate_pi(1000000)

which produces output:

ans =

    3.1399