Skip to content

Instantly share code, notes, and snippets.

@jeremyBanks
Created July 27, 2008 06:49
Show Gist options
  • Save jeremyBanks/2746 to your computer and use it in GitHub Desktop.
Save jeremyBanks/2746 to your computer and use it in GitHub Desktop.
Simple π calculation [2010-01] (from Pythagorean theorem)
#!/usr/bin/env python
# encoding: utf-8
from __future__ import division, with_statement
import sys
from math import sqrt, pi
def calculatePi(samples):
samples = int(samples)
if samples < 2:
raise ValueError("Minimum of two samples required.")
radius = 1
points = []
for n in range(samples):
x = (2 * n * radius / (samples - 1)) - radius
points.append((x, sqrt(radius ** 2 - x ** 2)))
perimiter = 0
for n in range(len(points) - 1):
perimiter += sqrt((points[n + 1][0] - points[n][0]) ** 2 + (points[n + 1][1] - points[n][1]) ** 2)
return perimiter / radius
def main():
print " Samples Calculated Variation"
print " ------- ---------- ---------"
sampleRange = list(range( 2, 10, 1))
sampleRange += list(range( 10, 100, 10))
sampleRange += list(range( 100, 1000, 100))
sampleRange += list(range( 1000, 10000, 1000))
sampleRange += list(range(10000, 100001, 10000))
for samples in sampleRange:
ourPi = calculatePi(samples)
print " %6i %9.7f %9.7f" % (samples, ourPi, ourPi - pi)
if __name__ == "__main__": sys.exit(main())
Samples Calculated Variation
------- ---------- ---------
2 2.0000000 -1.1415927
3 2.8284271 -0.3131655
4 2.9760677 -0.1655249
5 3.0352762 -0.1063165
6 3.0659554 -0.0756372
7 3.0842529 -0.0573398
8 3.0961950 -0.0453977
9 3.1044961 -0.0370966
10 3.1105417 -0.0310509
20 3.1315167 -0.0100760
30 3.1362561 -0.0053366
40 3.1381728 -0.0034198
50 3.1391652 -0.0024275
60 3.1397558 -0.0018368
70 3.1401405 -0.0014521
80 3.1404075 -0.0011852
90 3.1406016 -0.0009911
100 3.1407479 -0.0008447
200 3.1412963 -0.0002963
300 3.1414318 -0.0001609
400 3.1414883 -0.0001044
500 3.1415180 -0.0000746
600 3.1415359 -0.0000567
700 3.1415477 -0.0000450
800 3.1415558 -0.0000368
900 3.1415618 -0.0000309
1000 3.1415663 -0.0000263
2000 3.1415833 -0.0000093
3000 3.1415876 -0.0000051
4000 3.1415894 -0.0000033
5000 3.1415903 -0.0000024
6000 3.1415909 -0.0000018
7000 3.1415912 -0.0000014
8000 3.1415915 -0.0000012
9000 3.1415917 -0.0000010
10000 3.1415918 -0.0000008
20000 3.1415924 -0.0000003
30000 3.1415925 -0.0000002
40000 3.1415925 -0.0000001
50000 3.1415926 -0.0000001
60000 3.1415926 -0.0000001
70000 3.1415926 -0.0000000
80000 3.1415926 -0.0000000
90000 3.1415926 -0.0000000
100000 3.1415926 -0.0000000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment