Skip to content

Instantly share code, notes, and snippets.

@catupper
Created December 9, 2011 03:53
Show Gist options
  • Save catupper/1450078 to your computer and use it in GitHub Desktop.
Save catupper/1450078 to your computer and use it in GitHub Desktop.
pi
from decimal import getcontext , Decimal
from math import sqrt
def root(a):
x=Decimal(sqrt(a))
y=Decimal(0)
while(abs(x-y)>Decimal(0.1)**(getcontext().prec-1)):
x,y=x-(x*x-a)/(2*x),x
return x
def pi(keta):
getcontext().prec=keta
a=Decimal(1)
b=a/root(2)
t=a/4
p=a
x=Decimal(3)
y=a
while(abs(x-y)>Decimal(0.1)**(getcontext().prec-1)):
aa=(a+b)/2
b=root(a*b)
t=t-p*(a-aa)**2
p=p*2
a=aa
x,y=((a+b)*(a+b))/(4*t),x
return x
def main():
print pi(input())
if __name__=="__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment