Problem
To estimate π using the Monte Carlo method, we’ll utilize the concept of randomly generating points within a square and determining how many fall inside a quarter circle.
Monte Carlo Method
Lets do the setup:
- Imagine a square with side length 2 centered at the origin, with coordinates ranging from
(-1, -1)
to(1, 1)
. - Inside this square, there is a quarter circle of radius 1, also centered at the origin.
- The area of the square is 4 (since side length is 2), and the area of the quarter circle is (πr^2 / 4 = π/4) (since r=1).
i.e. Let B be area of square, and A be area of circle $$ B = 4r^2 $$
$$ A = \pi r^2 $$
$$ \frac{A}{B} = \frac{\pi}{4} $$
Now, we count the points
- Generate random points within the square.
- Count how many points fall inside the quarter circle.
- The proportion of points inside the quarter circle to the total number of points approximates the ratio of the areas, (π/4).
Estimating Pi
Let N
be the total number of points, and M
be the number of points inside the quarter circle.
$$ \frac{M}{N} ≈ \frac{π}{4} $$ $$ \implies π ≈ 4 \cdot \frac{M}{N} $$
Code
Java
|
|
Python
|
|
Complexity
- ⏰ Time complexity:
O(n)
, wheren
is the number of random points generated. - 🧺 Space complexity:
O(1)
Summary
The Monte Carlo method provides a simple yet effective way to estimate π by simulating random points within a specific range and calculating the ratio of points inside a quarter circle to the total number of points. The accuracy improves with an increase in the number of points generated.