import random
def approximate_pi(n):
# n - number of generated points, more points => more accuracy
number_of_points_in_circle = 0
total_number_of_points = 0
for _ in range(n):
x = random.uniform(0, 1)
y = random.uniform(0, 1)
# sqrt(x^2 + y^2) < 1 => (x,y) inside circle with r = 1; x^2 + y^2 < 1 => (x,y) inside circle
if (x**2 + y**2 < 1):
number_of_points_in_circle += 1
total_number_of_points += 1
# Pi * r^2 / (2r)^2 = number_of_points_in_circle / total_number_of_points (ratio of the area of a circle with radius r to the area of a square with side = 2r)
# r=1 => Pi = number_of_points_in_circle * 4 / total_number_of_points
return (number_of_points_in_circle * 4) / total_number_of_points
import codewars_test as test
# TODO Write tests
import solution # or from solution import example
# test.assert_equals(actual, expected, [optional] message)
@test.describe("Approximate Pi")
def test_group():
@test.it("test case")
def test_case():
test.assert_equals(round(approximate_pi(1000000), 2), 3.14)