Advertisement
Guest User

Series approximation of Pi in Python

a guest
Mar 14th, 2015
286
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.34 KB | None | 0 0
  1. # -*- coding: cp1252 -*-
  2.  
  3. from mpmath import *
  4. import time
  5.  
  6. dps = input("Number of decimals to compute: ")
  7. if dps < 11:
  8.     print "Choosing 11 digits"
  9.     dps = 11
  10.    
  11. mp.dps = dps
  12. mp.dps=mp.dps+1
  13.  
  14. a = 1
  15. x = 1
  16. b = mpf(1/mp.sqrt(2))
  17. c = 0.25
  18. i = 0
  19. y = 1
  20. derivedbefore = mpf(0)
  21. breakyn = False
  22. run = True
  23. #print "a =", a
  24. #print "x =", x
  25. #print "b =", b
  26. #print "c =", c
  27. #print "i =", i
  28. #print "Derived before:", derivedbefore
  29. start = time.clock()
  30. print "Start:", start
  31. print "------------------------------------------------------"
  32. print "------------------------------------------------------"
  33. while run == True:
  34.     i = i+1
  35.     y = mpf(a)
  36.     a = mpf((a+b)/2)
  37.     b = mpf(mp.sqrt(b*y))
  38.     c = mpf(c-x*(mp.power(a-y,2)))
  39.     x = mpf(2*x)
  40.     derived = mpf(mp.power((a+b),2)/(4*c))
  41.     if str(derived)[-10:-1] == str(derivedbefore)[-10:-1]:
  42.           break
  43.     print "Iteration:", i
  44.     #print
  45.     #print "Computed:", derived
  46.     derivedbefore = derived
  47.     print "------------------------------------------------------"
  48. stop=time.clock()
  49. print "------------------------------------------------------"
  50. print "Pi computed to ", mp.dps-1, "decimals:"
  51. print
  52. print derived
  53. duration=stop-start
  54. print "------------------------------------------------------"
  55. print "Time of execution: ", duration, "Seconds."
  56. print "Happy Pi Day!"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement