繁体   English   中英

python 中非常大的数字的舍入错误

[英]Rounding errors for very large numbers in python

用大量小数四舍五入非常大的数字会产生错误。 这种小数舍入的限制是什么? 我是 Python 的初学者,所以我不确定是否还有其他方法。

from decimal import *
print(round(Decimal((0.123456789123456789123456789123456789123)+12345678912345678912345678), 2))

Output:

12345678912345678704279552.00

注意 int 上的额外数字:

from decimal import *
print(round(Decimal((0.123456789123456789123456789123456789123)+123456789123456789123456789), 2))

Output:

回溯(最近一次通话最后):
文件“”,第 1 行,在
decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>]

与常见的误解相反, decimal模块不执行精确的算术运算。 它执行可调精度、十进制、浮点运算。

decimal模块默认为 28 位小数精度。 您请求的舍入操作至少需要 29 位精度,并且decimal不会默默地给您降低精度,而是针对此特定操作引发错误。

当然,您想要执行的运算涉及远高于 29 位的精度,但是因为您在float运算而不是decimal运算中完成了一半的数学运算,所以在decimal涉及之前,您就失去了大部分精度。 float的精度略低于 16 位十进制数字。 Decimal调用中包装float计算不会在Decimal算术中进行数学运算; 你需要Decimal开始:

import decimal
decimal.getcontext().prec = 100 # enough
print(round(decimal.Decimal('0.123456789123456789123456789123456789123')+
            decimal.Decimal('123456789123456789123456789'), 2))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM