Calculate Pi using python
Simple algorithm that calculates an approximation of pi. It is based on the idea that the area of a polygon with many sides circumscribed inside a unit circle approaches pi. In the example I test the algorithm with a polygon of 500 sides and the result of executing the code in my machine is 3.141592653589795Important Notes: The maximum length it can calculate is the number of decimal digits supported by Python. The program can be improved in order to accept arbitrary decimal points precision.
import math
def calcSide(a):
side = math.sqrt(2)
H = math.sqrt(1/2)
for x in range(1,a):
b = side/2
x = 1 - H
side = math.sqrt(b**2+x**2)
H = math.sqrt(1-(side/2)**2)
r = {"side":side,"H":H}
return r
def calcPi(a):
r = calcSide(a)
side = r["side"]
H = r["H"]
pi = (side*H*(2**(a+1)))/2
return pi
calcPi(500)
Written by jesuscast
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Python
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#