is it possible to use Monte carlo to compute the area of circle with a radius bigger than 1? i tried to make it this way but it only work for a circle of radius 1.
N = 10000
incircle = 0
count = 0
while (count<N)
x = random()
y = random()
if sqrt((x-a)^2 +(y-b)^2) <= R then
incircle = incircle+1
endif
count = count+1
so
Don't know what language you're using but I'll write following code in Python, hope you'll understand it.
I made computation for the case of area computation for circle of radius 2
.
Here Monte Carlo algorithm is as follows. Lets create a square having X
and Y
in range [-R ; R]
. Now lets randomly uniformly generate points inside this square.We will count total number of generated points and number of points inside a circle of radius R
bounded by given square. A point falls into circle if X^2 + Y^2 <= R^2
, otherwise its outside of circle. Finally area of square is (2 * R)^2
, while circle area is (approximately) equal to num_points_in_circle / num_points_total
-th part of area of a square.
In console output I also show error
which shows absolute difference with expected value computed precisely through formula Pi * R^2
.
In Python x ** 2
means x
raised to the power of 2
.
import random, math
R = 2
niters = 300_000
total, in_circle = 0, 0
for j in range(20):
for i in range(niters):
x = random.uniform(-R, R)
y = random.uniform(-R, R)
if x ** 2 + y ** 2 <= R ** 2:
in_circle += 1
total += 1
area = (2 * R) ** 2 * in_circle / total
expected = math.pi * R ** 2
print(f'After {(j + 1) * niters:>8} iterations area is {area:.08f}, ' +
f'error is {abs(area - expected):.08f}', flush = True)
Output:
After 300000 iterations area is 12.59130667, error is 0.02493605
After 600000 iterations area is 12.58341333, error is 0.01704272
After 900000 iterations area is 12.58072889, error is 0.01435827
After 1200000 iterations area is 12.57965333, error is 0.01328272
After 1500000 iterations area is 12.57741867, error is 0.01104805
After 1800000 iterations area is 12.57348444, error is 0.00711383
After 2100000 iterations area is 12.57067429, error is 0.00430367
After 2400000 iterations area is 12.57078000, error is 0.00440939
After 2700000 iterations area is 12.56853926, error is 0.00216864
After 3000000 iterations area is 12.56956800, error is 0.00319739
After 3300000 iterations area is 12.56826182, error is 0.00189120
After 3600000 iterations area is 12.56863111, error is 0.00226050
After 3900000 iterations area is 12.56763897, error is 0.00126836
After 4200000 iterations area is 12.56839238, error is 0.00202177
After 4500000 iterations area is 12.56855111, error is 0.00218050
After 4800000 iterations area is 12.56861667, error is 0.00224605
After 5100000 iterations area is 12.56857725, error is 0.00220664
After 5400000 iterations area is 12.56881185, error is 0.00244124
After 5700000 iterations area is 12.56925193, error is 0.00288132
After 6000000 iterations area is 12.56927733, error is 0.00290672