在Python 2中,rounding远离0
,因此,例如,round(0.5)
是1.0
。
但是,在Python 3.x中,rounding是朝着偶数选择方向进行的,因此round(0.5)
是0
。
我可以在Python 3.x中使用什么函数来获得旧的行为?
答案 0 :(得分:6)
如果您的代码对性能不是特别敏感,则可以使用标准的decimal
库来获得所需的结果。 Decimal().quantize()
允许选择舍入方法:
from decimal import Decimal, ROUND_HALF_UP
result = float(Decimal(0.5).quantize(Decimal(0), rounding=ROUND_HALF_UP))
print(result) # Will output 1.0
答案 1 :(得分:1)
要以{_1}}的单参数形式在Python 3中获得Python 2舍入行为,可以使用如下自定义函数:
round()
演示:
def myround(n):
if round(n + 1) - round(n) == 1:
return float(round(n))
return n + abs(n) / n * 0.5
答案 2 :(得分:1)
def round_up(x):
aX = abs(x)
return math.ceil(aX)*(aX/x)
此解决方案可能适合您。
对于x = -1.2 round_up(x) = -2
,x = 2.3 round_up(x) = 3
等
编辑:x = 0时,该解决方案将崩溃。您可以将返回值更改为
return math.ceil(aX)*(aX/x) if x is not 0 else 0
答案 3 :(得分:1)
舍入为整数(一个参数)时相当于Python 2.7 round()
:
import math
def py2round(x):
if x >= 0.0:
return math.floor(x + 0.5)
else:
return math.ceil(x - 0.5)
答案 4 :(得分:0)
这是我想出的一种可能的解决方案:
import math
def round_away_from_zero(x):
a = abs(x)
r = math.floor(a) + math.floor(2 * (a % 1))
return r if x >= 0 else -r
测试:
round_away_from_zero(0.5)
# 1
round_away_from_zero(1.5)
# 2
round_away_from_zero(2.5)
# 3
round_away_from_zero(-0.5)
# -1
round_away_from_zero(-1.5)
# -2
round_away_from_zero(-2.5)
# -3
答案 5 :(得分:0)
基本思想很简单:将double转换并四舍五入为a 使用_Py_dg_dtoa十进制字符串,然后转换该十进制字符串 回到_Py_dg_strtod的两倍。有一个小困难: Python 2.x希望取整可以从零开始取整,而 _Py_dg_dtoa会从一半变为一半。因此,我们需要某种方法来检测和纠正中途情况。
如果您关心性能,请考虑复制相关的C代码并将其作为扩展导入。但是,如果您不在乎,这是一个Python实现:
def myround(a):
num = str(a)
num = str.split('.', 1)
if int(num[1][0]) >= 5:
return int(num[0]) + 1 if a > 0 else int(num[0]) - 1
else:
return int(num[0]) - 1 if a > 0 else int(num[0]) + 1
答案 6 :(得分:-1)
与其他解决方案非常相似,但是使用速记 if 语句而不是函数:
segments = ceil(gamma / 90) if gamma > 0 else floor(gamma/90)