Guest User

Moores

a guest
Jan 9th, 2010
208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.54 KB | None | 0 0
  1. #!/usr/bin/env python
  2. #coding=utf-8
  3. # piByChudnovskyAlgorithm2.py
  4. # same as piByChudnovskyAlgorithm.py but with a loop
  5. # see The Chudnovsky algorithm at http://en.wikipedia.org/wiki/Chudnovsky
  6.  
  7. from mpmath import mp, mpf, pi
  8. import time
  9.  
  10. cached_factorials = [mpf(1)]
  11.  
  12. def f(n):
  13.     n = int(n)
  14.     if n < len(cached_factorials):
  15.         return cached_factorials[n]
  16.     p = cached_factorials[-1]
  17.     for i in range(len(cached_factorials), n+1):
  18.         p *= i
  19.         cached_factorials.append(p)
  20.     return p
  21.  
  22. print
  23. while True:
  24.     print \
  25.     """
  26.    Enter a positive integer to set precision.
  27.    Close program by entering a zero.
  28.    """
  29.    
  30.     precision = int(raw_input("integer: "))
  31.     if precision == 0:
  32.         print "Bye"
  33.         time.sleep(1)
  34.         break
  35.     timeStart = time.time()
  36.     mp.dps = precision
  37.     k = mpf(0)
  38.     term = 0
  39.     sum = 0
  40.     sumPrevious = 0
  41.     i = 0
  42.     while True:
  43.         i += 1
  44.         nom = (((-1)**k) * f(6*k) * (13591409+545140134*k))
  45.         denom = (f(3*k) * ((f(k))**3) * (640320**(3*k)))
  46.         term = nom/denom
  47.         sum += term
  48.         if sum == sumPrevious:
  49.             timeEnd = time.time()
  50.             print "The result calculated from the first %d terms of the series is:" % (i-1)
  51.             print 1/(12*sum/640320**(mpf(3)/2))
  52.             print
  53.             print "pi to %d digits is:" % precision
  54.             print pi
  55.             break
  56.         sumPrevious = sum
  57.         k += 1
  58.      
  59.     print "Time was %.4g seconds" % (timeEnd - timeStart)
  60.     print
  61.  
Advertisement
Add Comment
Please, Sign In to add comment