为什么Python十进制。小数精度与相等的args不同? [英] Why python decimal.Decimal precision differs with equable args?

查看:84
本文介绍了为什么Python十进制。小数精度与相等的args不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的输入内容:

>>> from decimal import Decimal
>>> Decimal('114.3')
Decimal('114.3')
>>> Decimal(114.3)
Decimal('114.2999999999999971578290569595992565155029296875')

我认为这两个Decimal实例必须相等,但带浮点arg的Decimal似乎会降低精度。为什么是这样?我的python版本是2.7.3。

I thought those two instances of Decimal have to be equal but Decimal with float arg seems to loose precision. Why is this? My python version is 2.7.3. Thanks in advance!

推荐答案

第二行为您提供二进制浮点数的精确十进制值,其近似值为114.3。这几乎与二进制浮点有关,而与十进制无关。有关详细信息,请参见文档

The second line is giving you the exact decimal value of the binary floating-point number which approximates 114.3. This is almost all about binary floating point, not much about Decimal. See the docs for details.

以后:如果使用的是Python 3,请改为参见这些文档。基本相同,但是Python 3提供了更多工具来帮助您探索像这样的情况。

Later: if using Python 3, see these docs instead. Same basic thing, but Python 3 has more tools to help you explore cases "like this".

这篇关于为什么Python十进制。小数精度与相等的args不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆