I'm beginner in Python, and I have one question.
Why does rounding a number like 5.5, 7.5, (anything).5 with odd integer part applying round(num)
work correctly (rule 5/4), but rounding number like (anything).5 with non-odd integer part by the same function returns just an integer part?
(But if we add a little number like 0.000000001 to that decimal number it works correctly)
I mean the next:
round(9.5)
returns 10, and it's correct. But
round(8.5)
returns 8, and it isn't correct. And
round(8.5 + 0.0000000000001)
returns 9.
Why it works incorrect?
I use Python 3.2.2 at Windows.
In Python there is a built-in round () function which rounds off a number to the given number of digits. The function round () accepts two numeric arguments, n and n digits and then returns the number n after rounding it to n digits. If the number of digits are not provided for rounding off, the function rounds off the given number n to ...
But that isn't a systematic error, not in the sense it happens to every integer. So I created the following Python script: And I can't see any pattern in the numbers for which this rounding error happens.
If you're looking to just round up regardless, the np.ceil function (ceiling function in general), will do this. If you're looking for the opposite (always rounding down), the np.floor function will achieve this. Good answer, do you happen to know how to get numpy to round up regardless of even or odd?
The most common form round-off error is the representation error in the floating point numbers. A simple example will be to represent π. We know that π is an infinite number, but when we use it, we usually only use a finite digits.
Python 3.x, in contrast to Python 2.x, uses Banker's rounding for the round()
function.
This is the documented behaviour:
[I]f two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2).
Since floating point numbers by their very nature are only approximations, it shouldn't matter too much how "exact" half-integers are treated – there could always be rounding errors in the preceding calculations anyway.
Edit: To get the old rounding behaviour, you could use
def my_round(x):
return int(x + math.copysign(0.5, x))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With