Python3 Decimal + round 函数 小坑

2019-07-22 17:29:22 +08:00
 djj510620510
from decimal import Decimal

round(Decimal(0.123456789), 3) + Decimal(0.01)  # out: Decimal('0.1330000000000000002081668171')

round(Decimal(0.123456789) + Decimal(0.01), 3)  # out: Decimal('0.133')

测试环境 python 3.6.5 + ipython

:D

2887 次点击
所在节点    Python
20 条回复
nooper
2019-07-22 17:35:14 +08:00
不是 python 的坑,是所有计算机指令的问题。 你在好好查一下,有专门的文档 decimal round_up 等处理这个问题。
chenstack
2019-07-22 17:36:49 +08:00
>>> round(Decimal('0.123456789'), 3) + Decimal('0.01')
Decimal('0.133')

Decimal 初始化时不要传 float 类型,要传字符串,因为传 float 时,float 值本身就有精度丢失问题
>>> Decimal(0.01)
Decimal('0.01000000000000000020816681711721685132943093776702880859375')
>>> Decimal('0.01')
Decimal('0.01')
lyy16384
2019-07-22 17:43:46 +08:00
我试了没有 round 也一样
Decimal(0.123) + Decimal(0.01)
chenstack
2019-07-22 17:54:30 +08:00
Construct a new Decimal object. 'value' can be an integer, string, tuple, or another Decimal object. If no value is given, return Decimal('0'). The context does not affect the conversion and is only passed to determine if the InvalidOperation trap is active.
XIVN1987
2019-07-22 18:01:44 +08:00
使用 decimal 不就是为了避免 float 的误差吗?

对 decimal 使用 round 不就把精确表示又带回了 float 的不精确表示了吗?
jingniao
2019-07-22 18:05:26 +08:00
对 decimal round 有自己的函数
djj510620510
2019-07-22 18:07:40 +08:00
@chenstack 感谢告知 :D

@XIVN1987 但是 round 返回的还是 decimal 类型
XIVN1987
2019-07-22 18:15:38 +08:00
@djj510620510
抱歉,我看错了,,我以为是把 decimal 加法结果传给了 round,,
djj510620510
2019-07-22 18:17:22 +08:00
@jingniao 还真是。。。。
djj510620510
2019-07-22 18:19:11 +08:00
@jingniao 但按照 python 设计理念,不是应该 Decimal 类里实现一个__round__吗,然后这个__round__的逻辑跟 decimal.round 的逻辑一样。
hjq98765
2019-07-22 18:25:50 +08:00
我还是为是说 [四舍六入五成双]
djj510620510
2019-07-22 18:43:19 +08:00
@hjq98765 应该 JS 才会出现吧 /doge
pkuphy
2019-07-22 19:27:21 +08:00
>>> round(1.5)
2
>>> round(2.5)
2
kxiaong
2019-07-22 20:25:48 +08:00
`round(Decimal("0.123456789"), 3) + Decimal("0.01") #Decimal('0.133')`

```
from decimal import *

getcontext().prec

```

不是 decimal 的坑, 初始化 decimal 变量,推荐使用 string 或者在运算时手动指定 percesion
1iuh
2019-07-22 20:29:16 +08:00
初始化 decimal 别传浮点数进去
1iuh
2019-07-22 20:29:42 +08:00
另外 decimal 有自己 round 方法。
hjq98765
2019-07-22 21:40:06 +08:00
@djj510620510 #12 原文:“@hjq98765 应该 JS 才会出现吧 /doge ”
======
回复:python3 也有这个坑,刚从 python2 转过来的时候着实被坑了一把
azh7138m
2019-07-22 21:42:54 +08:00
@djj510620510
> 四舍六入五成双

C++ 也会
yushi17
2019-07-22 21:49:58 +08:00
Marmot
2019-07-23 09:20:25 +08:00
因为你传进去的时候就不是精确的

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/585158

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX