如何像通常的学校四舍五入一样将0.5向上舍入为1.0,同时仍将0.45舍入为0.0? [英] How to round float 0.5 up to 1.0, while still rounding 0.45 to 0.0, as the usual school rounding?

查看:160
本文介绍了如何像通常的学校四舍五入一样将0.5向上舍入为1.0,同时仍将0.45舍入为0.0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎默认的Python round(1 / 2)给出了0.

Appears that the default Python round(1 / 2) gives 0.

如何将浮点数从0.5向上舍入为1.0,同时仍将0.45舍入为0.0,就像通常的学校舍入一样?

How to round float 0.5 up to 1.0, while still rounding 0.45 to 0.0, as the usual school rounding?

注意:很抱歉删除并再次发布,但错误地将其标记为另一个问题的重复项.

NOTE: Sorry for deleting and posting this again, but it was incorrectly marked as duplicate of another question.

推荐答案

实际上,目前认为不要盲目地* .5向上取整是合适的.相反,将* .5舍入到最接近的偶数是适当的. Python 3实现了银行取整"的这种适当"形式,但许多其他语言还没有(还).盲目舍入* .5会产生轻微的偏差,但是银行家舍入"有助于平衡它.有关更多信息,请参见此线程.所以...

It is actually currently considered proper to NOT blindly round *.5 up. Rather, it is proper to round *.5 to the nearest even number. Python 3 implements this "proper" form of "banker rounding", but a lot of other languages don't (yet). Blindly rounding *.5 up produces a slight bias, but "banker rounding" helps to balance it it out. See this thread for more info. So...

方法1

您可以有条件地使用ceil(...)函数(来自数学模块对于舍入方面.您必须有条件地执行此操作,以便还对小于0.5的值保持常规舍入行为.请尝试以下操作(请注意,此方法不是非常健壮,因为它仅在正值时有效).值...但是应该可以轻松地使其适用于正值和负值):

You could conditionally use aceil(...) function (from the math module for the rounding up aspect. You'll have to do it conditionally in order to also maintain the regular rounding behavior for values less than 0.5. Try something like the following (note that this isn't extremely robust in that it only works on positive values...it should be able to be easily adapted to work with both positive and negative values though):

import math

val = 1.5
x = 0

if (float(val) % 1) >= 0.5:
    x = math.ceil(val)
else:
    x = round(val)

请注意,ceil(...)函数将返回整数,而不是浮点数.这不是主要问题,但现在您知道了.

Note that a ceil(...) function will return an integer, not a float. This shouldn't be a major issue, but now you are aware.

方法2

从我上面链接到的帖子中,看来另一个选择是使用

From the post I linked to above, it looks like another option is to use the decimal module to emulate the "old" way of rounding's behavior. I'm kind of copy & pasting from there, but here you go:

import decimal

x = decimal.Decimal('1.5').quantize(decimal.Decimal('1'), 
rounding=decimal.ROUND_HALF_UP)

您想要的是decimal.ROUND_HALF_UP舍入形式.这样,您就不必有条件地使用ceil(...)函数.

Supposedly the decimal.ROUND_HALF_UP form of rounding is what you are looking for. This way you don't have to use a ceil(...) function conditionally.

我猜这被标记为另一个的重复,因为稍作挖掘就会为您提供有关此主题的足够信息. (我没有将其标记为重复项,我只是假设这就是其他人这样做的原因.)

这篇关于如何像通常的学校四舍五入一样将0.5向上舍入为1.0,同时仍将0.45舍入为0.0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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