Advertisement
Guest User

Monte Carlo - Pi - Python

a guest
Dec 1st, 2016
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.55 KB | None | 0 0
  1. import random
  2.  
  3. def withinCircle(x,y):
  4.     if(x**2+y**2<1):
  5.         return True
  6.     else:
  7.         return False
  8.  
  9. def main():
  10.     circleArea = 0.0
  11.     squareArea = 0.0
  12.     math = 3.14159
  13.     pi = 0.0
  14.     for i in range(0,100000):
  15.         x = random.random()
  16.         y = random.random()
  17.         if withinCircle(x,y):
  18.             circleArea=circleArea+1
  19.         squareArea=squareArea+1
  20.     pi = 4*circleArea/squareArea
  21.     print "Approximate value for pi: ", pi
  22.     print "Difference to exact value of pi: ", pi-math
  23.     print "Error: (approx-exact)/exact=", (pi-math)/math*100, "%"
  24.  
  25. if __name__ == "__main__":
  26.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement