Python中的Rounding如何工作?

Jon*_*ann 5 python floating-point precision rounding floating-accuracy

我对Python的舍入方式有点困惑.
有人可以解释为什么Python的行为如此?

例:

>>> round(0.05,1) # this makes sense
0.1
>>> round(0.15,1) # this doesn't make sense! Why is the result not 0.2?
0.1
Run Code Online (Sandbox Code Playgroud)

同样适用于:

>>> round(0.25,1) # this makes sense
0.3
>>> round(0.35,1) # in my opinion, should be 0.4 but evaluates to 0.3
0.3
Run Code Online (Sandbox Code Playgroud)

编辑:所以一般来说,Python可能会向下舍入而不是向上舍入.我是否理解可能发生的唯一"异常"事情是Python向下舍入?或者由于存储方式的原因,它是否也会"异常"四舍五入?(我还没有发现Python在我预期它向下舍入时被舍入的情况)

Ido*_*dos 12

这实际上是设计的.从Pythons的文档:

round()浮动的行为可能会令人惊讶:例如,round(2.675, 2)给出2.67而不是预期的2.68.这不是一个错误:这是因为大多数小数部分不能完全表示为浮点数.

  • 是,特别是"0.15"在内部表示为"0.1499999999999999944488848768742172978818416595458984375","0.35"是"0.34999999999999997779553950749686919152736663818359375".两者都合理地向下舍入. (5认同)
  • @JonasKaufmann - `print round(0.6499999999999999999,1)`. (2认同)

Gal*_*lax 8

听起来像你需要这个decimal模块:

from decimal import *
x = Decimal('0.15')
print x.quantize(Decimal('0.1'), rounding=ROUND_HALF_UP)
Run Code Online (Sandbox Code Playgroud)

输出:

0.2
Run Code Online (Sandbox Code Playgroud)