gpt4 book ai didi

Python Decimal 类型精度错误

转载 作者:太空宇宙 更新时间:2023-11-04 01:15:28 24 4
gpt4 key购买 nike

我有一个非常令人费解的问题,我怀疑它与科学记数法和小数精度有关。这是我的部分代码:

    def atan(x):
# Calculate arctan(1/x)
x = Decimal(x)
current_value = Decimal(0)
divisor = 1
x_squared = x * x
current_term = 1 / x


while True:
current_value += current_term

divisor += 2
current_term = (-current_term / x_squared) / divisor
print(current_term)

# The issue
if current_term == Decimal(0):
break

return current_value

print(atan(5))

这是基于公式 atan(1/x) = 1/x - 1/(3x^3) + 1/(5x^5) - ...

但是,我发现 current_term 在每次循环迭代时都会变小,并且会变成 4E-80000 这样的值。由于我已将小数精度 getcontext().prec 设置为 20,当前术语甚至不应该支持这些值。我觉得current_term不知何故不是小数类型而是科学记数法/ float 类型,但是python告诉我它仍然是小数类型。

arctan(1/5) 的正确值约为 0.1973955。我得到的值为 0.1973545,从第 5 位开始是错误的。即使我手动中断循环,由于某种原因该值仍然是错误的。 解决此问题的任何帮助表示赞赏。

最佳答案

您的代码与公式不匹配。从下一个术语推断一个术语有点太棘手了;-) 1/(5x^5) term 不是 1/(3x^3) 的倍数术语。

这是直接对公式建模的代码:

from decimal import Decimal

def atan_recip(x):
# Calculate arctan(1/x)
x = Decimal(x)

total = Decimal(0)
sign = 1
for i in range(1, 35, 2):
total += sign / (i * x ** i)
sign = -sign
print(total)

atan_recip(5)

输出是你所期望的:

0.2
0.1973333333333333333333333333
0.1973973333333333333333333333
0.1973955047619047619047619047
0.1973955616507936507936507936
0.1973955597889754689754689754
0.1973955598519908535908535908
0.1973955598498063202575202575
0.1973955598498834214339908457
0.1973955598498806620234645299
0.1973955598498807618878454823
0.1973955598498807582406246127
0.1973955598498807583748423407
0.1973955598498807583698713137
0.1973955598498807583700564416
0.1973955598498807583700495142
0.1973955598498807583700497745

关于Python Decimal 类型精度错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24967744/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com