Python3 rounding to nearest even

后端 未结 3 1668
悲哀的现实
悲哀的现实 2020-12-31 02:54

Python3.4 rounds to the nearest even (in the tie-breaker case).

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

But it only seems to do

相关标签:
3条回答
  • 2020-12-31 03:31

    Floating point numbers are only approximations; 2.85 cannot be represented exactly:

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

    It is slightly over 2.85.

    0.5 and 0.75 can be represented exactly with binary fractions (1/2 and 1/2 + 1/4, respectively).

    The round() function 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.

    0 讨论(0)
  • 2020-12-31 03:38

    To answer the title... If you use int(n), it truncates towards zero. If the result is not even, then you add one:

    n = 2.7     # your whatever float
    result = int(n)
    if not (result & 1):     
        result += 1
    
    0 讨论(0)
  • 2020-12-31 03:50

    Martijn got it exactly right. If you want an int-rounder to round to the nearest even, then I would go with this:

    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
    
    0 讨论(0)
提交回复
热议问题