Python 需要匹配精确的十进制输出

Python 需要匹配精确的十进制输出,python,algorithm,Python,Algorithm,德国数学家戈特弗里德·莱布尼茨(Gottfried Leibniz)提出了以下近似π值的方法: π/4=1-1/3+1/5-1/7+ 编写一个程序,允许用户指定此近似中使用的迭代次数,并显示结果值 程序输入和输出示例如下所示: 输入迭代次数:5 pi的近似值为3.3396825396825403 iteration = int(input("Enter the number of iteration: ")) list01 = [] list02 =

德国数学家戈特弗里德·莱布尼茨(Gottfried Leibniz)提出了以下近似π值的方法:

π/4=1-1/3+1/5-1/7+

编写一个程序,允许用户指定此近似中使用的迭代次数,并显示结果值

程序输入和输出示例如下所示:

输入迭代次数:5

pi的近似值为3.3396825396825403

    iteration = int(input("Enter the number of iteration: "))
    list01 = [] 
    list02 = []
    y = 1
    for x in range(1, iteration+1):
        number = (1.0/y)
        list01.append(number)
        y += 2.0
        #print(number)
    for i in range(1, iteration, 2):
        neg = list01[i]*-1.0
        list02.append(neg)
        #print(neg)
    comb = (sum(list01)) + (sum(list02)) + (sum(list02))
    pi = comb*4.0
    print("The approximation of pi is", pi)
此代码用于:

1次迭代,输出为4.0,与4的所需输出相匹配

5次迭代,输出为3.339682539682539,与要求的输出3.3396825396825403不匹配

    iteration = int(input("Enter the number of iteration: "))
    list01 = [] 
    list02 = []
    y = 1
    for x in range(1, iteration+1):
        number = (1.0/y)
        list01.append(number)
        y += 2.0
        #print(number)
    for i in range(1, iteration, 2):
        neg = list01[i]*-1.0
        list02.append(neg)
        #print(neg)
    comb = (sum(list01)) + (sum(list02)) + (sum(list02))
    pi = comb*4.0
    print("The approximation of pi is", pi)
10次迭代,输出为3.0418396189294015,与要求的输出3.0418396189294032不匹配


999次迭代,输出为3.1425936543400352,与要求的输出3.142593654340044不匹配

如果需要避免精度问题,请使用
decimal.decimal
。或者在这种情况下,可以使用
fracts.fracts
s,并在最后转换为
float
(在此之前它将保持一个完全精确的中间结果)。旁注:此代码的精确结果,大多数代码使用
fracts
,最后转换为
Decimal
以生成类似浮点的输出是
3.339682539682539682539682540
,持续五次迭代(注意重复的
396825
组件;如果
Decimal
没有切断它,我希望它会永远重复)。以
403
结尾的所需输出是错误的(您的输出更正确),除非他们希望您有浮点精度问题,在这种情况下,这是一个糟糕的提示(以稍微不同的方式执行正确的工作将得到不同的浮点精度错误).@ShadowRanger谢谢你,我试着在分数和小数上乱搞,但没有得到准确的答案。这可能是个好答案,但试着添加一个解释。完美的答案。非常感谢,请解释一下。具体来说,
negative=False
negative=not negative
我添加了说明,并用更多信息变量更改了代码。
"""pure step by step Leibniz idea
'sign'-- sign switcher. If you need the sum of even divisors 
summ +1/1 (n=0), +1/5 (n=2), +1/9 (n=4), sign is True.
With each odd divisible, 'sign' changes to False, changing the 
sign of the next term, summ -1/3 (n=1), -1/7 (n=3), -1/11 (n=5), etc..
"""

iteration = int(input("n: "))
presumm = 0
div = 1
sign = True
for i in range(iteration):
    presumm = presumm + 1 / div if sign else presumm - 1 / div
    div += 2
    sign = not sign
pi = presumm * 4
print(pi)

# n==5,   output: 3.3396825396825403
# n==10,  output: 3.0418396189294032
# n==999, output: 3.142593654340044