Skip to content

Instantly share code, notes, and snippets.

@envil
Created October 12, 2018 05:27
Show Gist options
  • Save envil/26625853afb4a65def0b995f409d9640 to your computer and use it in GitHub Desktop.
Save envil/26625853afb4a65def0b995f409d9640 to your computer and use it in GitHub Desktop.
Monte Carlo circle area calculator
import numpy as np
import math
def test(iteration):
radius = np.random.randint(0, 1000)
sum_area = 0
for i in range(iteration):
x = np.random.uniform(-radius, radius)
y = math.sqrt(radius * radius - x * x)
sum_area = sum_area + radius * 2 * y
average_area = 2 * sum_area / iteration
math_area = math.pi * radius * radius
deviation = math_area - average_area
error = abs(100 * deviation / math_area)
print(f'radius = {radius}, math_area = {math_area}, {iteration} iterations')
print(f'average_area = {average_area}, deviation = {deviation}, error = {round(error, 2)}%')
k = []
for i in range(1, 5):
k.append(int(math.pow(10, i)))
for i in k:
test(i)
radius = 106, math_area = 35298.93505573492, 10 iterations
average_area = 36999.59528245894, deviation = -1700.6602267240232, error = 4.82%
radius = 252, math_area = 199503.69987356622, 100 iterations
average_area = 204652.89349130393, deviation = -5149.1936177377065, error = 2.58%
radius = 409, math_area = 525528.7606851542, 1000 iterations
average_area = 520319.43752884277, deviation = 5209.323156311468, error = 0.99%
radius = 861, math_area = 2328928.6075518387, 10000 iterations
average_area = 2323212.544995661, deviation = 5716.062556177843, error = 0.25%
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment