# Demo entry 2333714

random pi

Submitted by anonymous on Jul 27, 2015 at 10:02
Language: Python. Code size: 1.0 kB.

```import math
import random

pi_string = "3.141592653589793238462643383279502884197169399375105820974944"

print 'Content-Type: text/plain'
print ''
TRIES = 1000
print 'Pi coming from Randomness of Pi (%d tries)' %TRIES

# print "We have %d digits of Pi so let's try up to %d tries!" %(len(pi_string)-2, (len(pi_string)-2)/10)
print ''

def calculate_pi(no):
hit = 0
for i in range(no):
if math.sqrt(random.random()**2+random.random()**2) <= 1:
hit += 1
return 4.0*hit/no

def random_pi(length,seed):
index = 2 + seed * length
result = float("0."+pi_string[index:index+length])
return result

def calculate_pi2(no):
hit = 0
for i in range(no):
if math.sqrt(random_pi(10,i*2)**2+random_pi(10,(i*2)-1)**2) <= 1:
hit += 1
result = 4.0*hit/no
return result

pi_rnc = calculate_pi(TRIES)
pi_pi = calculate_pi2(TRIES)

print "Python RNC: %2.5f, diff: %2.5f" %(pi_rnc, abs(math.pi-pi_rnc))
print "Random Pi : %2.5f, diff: %2.5f" %(pi_pi, abs(math.pi-pi_pi))
```

This snippet took 0.00 seconds to highlight.

Back to the Entry List or Home.