The calculation would be simplified if you centered the circle at the origin. Also, by symmetry, you only need to model one quadrant.
import random
TIMES_TO_REPEAT = 10**5
LENGTH = 10**5
def in_circle(x, y):
return x**2 + y**2 < LENGTH**2
inside_count = 0
for _ in range(TIMES_TO_REPEAT):
point = random.randint(0,LENGTH), random.randint(0,LENGTH)
if in_circle(*point):
inside_count += 1
pi = (inside_count / TIMES_TO_REPEAT) * 4
print(pi)
A few other remarks:
iis unused; you can call the iteration variable_.countwill eventually beTIMES_TO_REPEAT, so you don't have to derive it by incrementing.*pointspares you from having to unpackpoint[0]andpoint[1].- If you require points to be strictly inside the circle (comparing using < rather than ≤), it seems fair to use 0 instead of 1 as the lower bound.
However, it seems that using floating-point numbers increases accuracy more efficiently than longer integer values of LENGTH. So, we can use the unit circle, and get rid of one arbitrary constant.
TIMES_TO_REPEAT = 5000000
def in_circle(x, y):
return x**2 + y**2 < 1
inside_count = 0
for _ in range(TIMES_TO_REPEAT):
point =if in_circle(random.random(), random.random()
if in_circle(*point):
inside_count += 1
pi = (inside_count / TIMES_TO_REPEAT) * 4