如何计算格雷戈里级数和 math.pi 的误差

How to calculate Gregory series and the error with math.pi

我的代码需要帮助。我想写一个代码,可以计算出"math.pi and pi using Gregory series"的误差。误差范围是1.0E-1~1.0E-8。这是我的代码:

import math
EPSILON=0.1
def ans(terms):
    result=0.0
    for n in range(terms):
        result+=(-1.0)**n/(2.0*n+1.0)
    return 4*result
    if abs(pi-ans)<=EPSILON:
        print n,ans,abs(pi-ans)
    else:
        print("out of different")

我可以得到答案,比如ans(60) >>> 3.1249271439289967,但是我无法得到print n,ans,abs(pi-ans)的输出,我的代码有什么问题?

这是因为您的打印语句是缩进的,这使它们成为您 ans() 函数的一部分。 您的代码还有其他几个错误

  • 你不能只使用 pi 但应该使用 math.pi
  • 你在你的 print 语句中调用了 ans 而没有使用参数

您的代码应如下所示:

import math
EPSILON=0.1
def ans(terms):
    result=0.0
    for n in range(terms):
        result+=(-1.0)**n/(2.0*n+1.0)

    return 4*result

n = 60
res = ans(n)
if abs(math.pi-res) <= EPSILON:
    print n,res,abs(math.pi-res)
else:
    print("out of different")