Android / Kotlin Enthusiast 🤖

Calculate Pi by Monte Carlo Methods

Off course it is difficult to calculate the exact value of pi, but a simple approximation can be calculated by Monte Carlo methods.

Monte Carlo methods, or Monte Carlo experiments, are a broad class of computational algorithms that rely on repeated random sampling to obtain numerical results. (Wikipedia)

A well known idea is using the ratio of areas of a square and an inscribed circle to it (Fig-1).

Fig-1 calculating pi

If a random coordinate inside a square generated, the probability that the coordinate locates inside the inscribed circle would be $\frac{\pi}{4}$. Assume that the radius of the inscribed circle is $r$. The area of the square is $4r^2$ and the area of the circle is ${\pi}r^2$. So, the ratio of the two areas is $\frac{\pi}{4}$. Putting the probability as $p$, $p = \frac{\pi}{4}$ and its for ${\pi}$ as ${\pi} = 4p$.

As the radius is erased from the ratio, any radius would do. So using 1 as radius would help to simplify the problem. Also, because the square and circle is point symmetric, considering the first quadrant is enough. When we puth the radius 1, the formula for determining if the random coordinate is inside the circle or not is represented as $\sqrt{{x}^2 + {y}^2} \leqq 1$. By squaring both sides, we get ${x}^2 + {y}^2 \leqq 1$.

Finally, we could implement the calculation as below. It output 3.1419424 and it’s close to pi.

import random

count = 0
attempt = 10**7

for _ in range(attempt):
    # random.random() generates random floating point value with [0, 1)
    x = random.random()
    y = random.random()
    if x**2 + y**2 <= 1:
        count += 1

p = count / attempt
pi = 4 * p
print(pi) # 3.1419424

OK we could calculated an approximation of pi by Monte Carlo methods.


  1. Monte Carlo method - Wikipedia


About me 😎



Jetpack ComposeによるAndroid MVVMアーキテクチャ入門の著者です。

👉 もっと詳しく

Writing 📝

Android MVVMアーキテクチャ入門


👉 もっと詳しく

See Also 👀