原题:
代码:
import math
print("pi = %f" % math.pi)
pi = 1
n = 1
c = 1
delta = abs(2*pi - math.pi)
while(delta >= 0.00001):
c *= n / (2*n+1)
pi += c
delta = abs(2*pi - math.pi)
print("Calculate #%d : pi = %f, delta = %f" % (n, 2*pi, delta))
n += 1
示例输出:
$ python pi.py
pi = 3.141593
Calculate #1 : pi = 2.666667, delta = 0.474926
Calculate #2 : pi = 2.933333, delta = 0.208259
Calculate #3 : pi = 3.047619, delta = 0.093974
Calculate #4 : pi = 3.098413, delta = 0.043180
Calculate #5 : pi = 3.121501, delta = 0.020092
Calculate #6 : pi = 3.132157, delta = 0.009436
Calculate #7 : pi = 3.137130, delta = 0.004463
Calculate #8 : pi = 3.139470, delta = 0.002123
Calculate #9 : pi = 3.140578, delta = 0.001014
Calculate #10 : pi = 3.141106, delta = 0.000487
Calculate #11 : pi = 3.141358, delta = 0.000234
Calculate #12 : pi = 3.141480, delta = 0.000113
Calculate #13 : pi = 3.141538, delta = 0.000055
Calculate #14 : pi = 3.141566, delta = 0.000026
Calculate #15 : pi = 3.141580, delta = 0.000013
Calculate #16 : pi = 3.141586, delta = 0.000006