Estimating the value of $\pi$ with a Monte Carlo dartboard: $<$ or $\leq$?

I'm trying to figure out which is the proper way to estimate $\pi$ using the Monte Carlo method randomly distributing points in a square that also contains an inscribed circle.

Some sources say to use the comparison of $\sqrt{x^2+y^2}\le 1$, while others use $\sqrt{x^2+y^2}1$.

Here's some example code from a wikipedia article:

def monte_carlo_pi(nsamples):
    acc = 0
    for i in range(nsamples):
        x = random.random()
        y = random.random()
        if (x**2 + y**2)  1.0:
            acc += 1
    return 4.0 * acc / nsamples

Instead of posting a long list of websites that use $\le 1$ or $ 1$, I've made the list and stored it on the following websites: See either: socrates.io or markdown.press or markdownshare for examples using less than and less than or equal to.

Topic mathematics monte-carlo simulation

Category Data Science


Short answer: Both formulations lead to the same answer.


Mathematical explanation:

In order to understand that let us look at two similar problems. Imagine we want to integrate a function $f(x)=x^2$ on two intervals $I_1=[0,1]$ (including both bounds) and $I_2=(0,1)$ (excluding both bounds).

For $I_1$ we have

$$\int_0^1 x^2~dx=1/3.$$

For the second interval, we need to introduce a positive dummy parameter $\varepsilon$ then we can calculate the integral as

$$\lim_{\varepsilon\to 0}\int_{0+\varepsilon}^{1-\varepsilon}x^2~dx=1/3.$$

So the line of separation between both intervals does not contribute to the integral (area) because it has an infinitesimal width. The same argument can be applied to the circle area. But including the line of the circle will make the calculations easier because we do not need to introduce a dummy variable.


Numerical explanation:

Because of the numerical precision of your computer, it will be very unlikely that the generated random numbers will lead to points that are really on the line of the circle. Numerically it will be impossible to obtain any value in which at least one of the coordinates is irrational. Only if both values are rational and if $x^2+y^2=1$ they can lie on the circle. But this case is also very unlikely.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.