Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Calculate Pi

This script presents a way to compute Pi using a statistic method.
See http://en.wikipedia.org/wiki/Computing_π for further algorithms.

   1  
   2  import random, math
   3  
   4  class calcPi:
   5      def __init__(self):
   6          self.times = pow(10,6)
   7          self.i = 0
   8          self.isnot = 0
   9  
  10      def IsOnCircle(self,x,y):
  11          if math.sqrt(x**2+y**2) < 1:
  12              return True
  13          else:
  14              return False
  15      
  16      def run(self):
  17          for x in range(self.times):
  18              x,y = random.random(),random.random()
  19              if self.IsOnCircle(x,y):
  20                  self.i+=1
  21              else:
  22                  self.isnot+=1
  23      
  24      def getResults(self):
  25          return (float(self.i), float(self.isnot))
  26  
  27      def getPi(self):
  28          self.run()
  29          r = self.getResults()
  30          return r[0]/(r[0]+r[1])*4
  31  
  32  if __name__ == '__main__':
  33      print calcPi().getPi()
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS