Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- #coding=utf-8
- # piByChudnovskyAlgorithm2.py
- # same as piByChudnovskyAlgorithm.py but with a loop
- # see The Chudnovsky algorithm at http://en.wikipedia.org/wiki/Chudnovsky
- from mpmath import mp, mpf, pi
- import time
- cached_factorials = [mpf(1)]
- def f(n):
- n = int(n)
- if n < len(cached_factorials):
- return cached_factorials[n]
- p = cached_factorials[-1]
- for i in range(len(cached_factorials), n+1):
- p *= i
- cached_factorials.append(p)
- return p
- print
- while True:
- print \
- """
- Enter a positive integer to set precision.
- Close program by entering a zero.
- """
- precision = int(raw_input("integer: "))
- if precision == 0:
- print "Bye"
- time.sleep(1)
- break
- timeStart = time.time()
- mp.dps = precision
- k = mpf(0)
- term = 0
- sum = 0
- sumPrevious = 0
- i = 0
- while True:
- i += 1
- nom = (((-1)**k) * f(6*k) * (13591409+545140134*k))
- denom = (f(3*k) * ((f(k))**3) * (640320**(3*k)))
- term = nom/denom
- sum += term
- if sum == sumPrevious:
- timeEnd = time.time()
- print "The result calculated from the first %d terms of the series is:" % (i-1)
- print 1/(12*sum/640320**(mpf(3)/2))
- print
- print "pi to %d digits is:" % precision
- print pi
- break
- sumPrevious = sum
- k += 1
- print "Time was %.4g seconds" % (timeEnd - timeStart)
- print
Advertisement
Add Comment
Please, Sign In to add comment