Python中的舍入是如何工作的? [英] How does Rounding in Python work?

查看:176
本文介绍了Python中的舍入是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



示例:

我对Python中的四舍五入方式有点困惑。 / p>

 >>> round(0.05,1)#这是有道理的
0.1
>>>轮(0.15,1)#这没有任何意义!为什么结果不是0.2?
0.1

同样的:

 >>> round(0.25,1)#这是有道理的
0.3
>>> (0.35,1)#在我看来应该是0.4但是评估为0.3
0.3



<所以一般来说,Python可能会舍弃而不是四舍五入。所以我才明白,唯一可能发生的异常事情是Python缩小?或者由于存储方式的不同,也可能会异常地四舍五入? (我还没有发现一个Python预计它圆整的情况,这个例子就是一个例子)

解决方案

这实际上是通过设计。来自Pythons的文档


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



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)

解决方案

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.

这篇关于Python中的舍入是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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