Skip to content

Instantly share code, notes, and snippets.

@accessnash
Created October 4, 2020 15:45
Show Gist options
  • Select an option

  • Save accessnash/4f223d061b0ed33dbf519395eceebeff to your computer and use it in GitHub Desktop.

Select an option

Save accessnash/4f223d061b0ed33dbf519395eceebeff to your computer and use it in GitHub Desktop.
Calculate Pi using acceptance-rejection
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 4 17:31:12 2020
@author: Localuser
"""
from random import uniform
from math import sqrt
def random_throw(radius):
random_x = uniform(-radius, radius)
random_y = uniform(-radius, radius)
if sqrt(random_x**2 + random_y**2) <= radius:
within_circle = True
else:
within_circle = False
return random_x, random_y, within_circle
no_of_throws = 100
count_in_circle = 0
for i in range(no_of_throws):
*_, within_circle = random_throw(1)
if within_circle:
count_in_circle += 1
print(f'Pi is approximately equal to: {(4*count_in_circle) /no_of_throws}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment