Python3 四舍五入至最近偶数

2024-10-01 22:40:17 发布

您现在位置:Python中文网/ 问答频道 /正文

Python3.4发到最接近的偶数(在决胜局的情况下)。在

>>> round(1.5)
2
>>> round(2.5)
2

但它似乎只有在四舍五入到整数时才会这样做。在

^{pr2}$

在上面的最后一个例子中,当四舍五入到最接近的偶数时,我希望答案是2.8。在

为什么这两种行为之间存在差异?在


Tags: 答案情况整数差异例子偶数roundpr2
3条回答

回答题目。。。如果使用int(n),则它将向零截断。如果结果不是偶数,则添加一个:

n = 2.7     # your whatever float
result = int(n)
if not (result & 1):     
    result += 1

马蒂恩说得对。如果你想让一个整数取整到最接近的偶数,那么我会用这个:

def myRound(n):
    answer = round(n)
    if not answer%2:
        return answer
    if abs(answer+1-n) < abs(answer-1-n):
        return answer + 1
    else:
        return answer - 1

浮点数只是近似值;2.85不能精确表示

>>> format(2.85, '.53f')
'2.85000000000000008881784197001252323389053344726562500'

略大于2.85。在

0.5和0.75可以用二元分数(分别为1/2和1/2+1/4)精确表示。在

round()函数documents this explicitly

Note: 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. See Floating Point Arithmetic: Issues and Limitations for more information.

相关问题 更多 >

    热门问题