Approximation of Pi (Python)

Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
vegaseat vegaseat is online now Online Mar 26th, 2006, 3:04 pm |
0
For those of you who are inquisitive, here is a little Python program to approximate the value of pi to 77 digits. You can easily go further, just change the value n in range(n+1).
Quick reply to this message  
Python Syntax
  1. # a generator to approximate pi to n decimals
  2. # the result is a string
  3. # tested with Python24
  4.  
  5. def pi_generate():
  6. """generator to approximate pi"""
  7. q, r, t, k, m, x = 1, 0, 1, 1, 3, 3
  8. while True:
  9. if 4 * q + r - t < m * t:
  10. yield m
  11. q, r, t, k, m, x = (10*q, 10*(r-m*t), t, k, (10*(3*q+r))//t - 10*m, x)
  12. else:
  13. q, r, t, k, m, x = (q*k, (2*q+r)*x, t*x, k+1, (q*(7*k+2)+r*x)//(t*x), x+2)
  14.  
  15. n = 77
  16. digits = pi_generate()
  17.  
  18. # build a list of characters, the leading 3 and n decimals
  19. pi_list = []
  20. for i in range(n+1):
  21. pi_list.append(str(digits.next()))
  22.  
  23. # insert the missing period at index 1 (after the 3)
  24. pi_list.insert(1, '.')
  25.  
  26. #print pi_list # test
  27.  
  28. # convert the list of characters to a string
  29. pi_str = "".join(pi_list)
  30.  
  31. print "pi approximated to %d decimals (below it is the official pi):" % n
  32. print pi_str
  33. # official pi value
  34. pi_pub = "3.14159265358979323846264338327950288419716939937510582097494459230781640628620"
  35. print pi_pub
  36.  
  37. """
  38. result -->
  39. pi approximated to 77 decimals (below it is the official pi):
  40. 3.14159265358979323846264338327950288419716939937510582097494459230781640628620
  41. 3.14159265358979323846264338327950288419716939937510582097494459230781640628620
  42. """
0
vegaseat vegaseat is online now Online | Jan 13th, 2007
Switched to a highly efficient generator function and added more comments.
 
0
jrcagle jrcagle is offline Offline | Jan 21st, 2007
Do you have a link for this particular algorithm?

Thanks,
Jeff
 
0
vegaseat vegaseat is online now Online | Feb 5th, 2007
Sorry Jeff, don't have a link. This is from one of the many series expansions that float around the net. I know it is accurate for at least 77 places. I did add a comparison with the published real pi to it.

In the mean time a happy '4*math.atan(1)' to you!
 
0
kogorman kogorman is offline Offline | Nov 18th, 2008
Here's a link to something that looks like it might have been the original.

http://mail.python.org/pipermail/edu...ly/006810.html

This page contains a link to a math paper (PDF) where the idea was developed.
 
 

Message:


Thread Tools Search this Thread



Tag cloud for Python
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC