How does Rounding in Python work?

浪子不回头ぞ 提交于 2019-12-23 10:28:11

问题


I am a bit confused about how rounding in Python works.
Could someone please explain why Python behaves like this?

Example:

>>> 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

And same for:

>>> 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

Edit: So in general, there is a possibility that Python rounds down instead of rounding up. So am I to understand that the only "abnormal" thing that can happen is that Python rounds down? Or may it also get rounded up "abnormally" due to how it is stored? (I haven't found a case where Python rounded up when I expected it to round down)


回答1:


This is actually by design. From Pythons' documentation:

The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float.




回答2:


It sounds to me like you need the decimal module:

from decimal import *
x = Decimal('0.15')
print x.quantize(Decimal('0.1'), rounding=ROUND_HALF_UP)

Output:

0.2



回答3:


As an example, here is a case where you get rounding up:

>>> round(0.0499999999999999999,1)
0.1

In this case, 17 "9"s are the minimum number to cause this behavior. This is because the internal representation of 0.0499999999999999999 is 0.05000000000000000277555756156289135105907917022705078125.



来源:https://stackoverflow.com/questions/34620633/how-does-rounding-in-python-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!