Posted By

DavidAspden on 09/28/18


Tagged

math random pi


Versions (?)

Estimate Pi


 / Published in: Python
 

So we use the fact that given a quarter circle of radius 1 we can generate random numbers and test whether they are inside the circle or outside. The probability that they are inside is pi/4 so we can run a large number of trials to get an approximation to Pi.

  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Thu Sep 27 16:52:34 2018
  5. """
  6.  
  7. ######Estimate pi
  8.  
  9. ###import the maths
  10. from math import *
  11. from random import *
  12.  
  13. ###Pi Calculating Function
  14. ###n is the number of trials
  15. def pimaker(n):
  16. #Our counter is initialised
  17. ins=0
  18.  
  19. for i in range (n):
  20. #random number generation
  21. x=random()
  22. y=random()
  23.  
  24. ##calc and test the inequality
  25. if sqrt(x**2 + y**2)<1:
  26. #inside, so increment the counter
  27. ins=ins+1
  28. #Now just pretty print the estimate doing inline calculation.
  29. print("Our estimate of pi is ", 4*(ins/n))
  30.  
  31. #Test The Function with various precision as below.
  32.  
  33. #pimaker(5)
  34. #pimaker(10000000)

Report this snippet  

You need to login to post a comment.