通过泰勒展开估计pi的错误

问题描述 投票:0回答:1

我试图计算pi的值,但我的逻辑中存在一些语义错误,我无法弄清楚。

def taylor(precision):
    iter = 1
    sum = 0
    fx = 100
    sign = 1

    while (abs(fx) > precision):

        if not iter % 2 == 0:
            print(sign)
            sum += ((1 / (iter)) * sign)

        my_pi = 4 * (sum)
        fx = math.pi - my_pi
        iter += 1
        sign *= -1

    return my_pi

这导致无限循环。

我应该使用这个系列,并找到my_pi特定的精度:

π/ 4 =(1/1) - (1/3)+(1/5) - (1/7)+(1/9) - ......

编程很新,任何帮助都会很棒!

python function math taylor-series
1个回答
1
投票

这部分在这里

if not iter % 2 == 0:

意味着你只在迭代不是偶数时才求和,即1,3,5,....但是,你每次迭代都会交替使用符号,包括偶数迭代的符号。

结果,你得到1/1 + 1/3 + 1/5 + ...

相反,试试吧

        if not iter % 2 == 0:
            print(sign)
            sum += ((1 / (iter)) * sign)
            sign *= -1 # move the sign assignment here
© www.soinside.com 2019 - 2024. All rights reserved.