The functions execute different mathematical operations:
-
round()
rounds a float value to the nearest integer. If either of the two integers on either side are equal distance apart, the even number is picked.Here, the nearest integer is always
-6
; for-5.5
the nearest even integer is-6
, not-5
. -
math.ceil()
returns the smallest integer greater than or equal to the float value.Here, the next integer greater than the inputs is always
-5
(remember that negative numbers decrease away from zero).
I think the biggest confusion you have comes from the even rounding rule. Had you picked -4.5
, you’d have seen round()
return -4
:
>>> import math
>>> math.ceil(-4.5)
-4
>>> round(-4.5)
-4
From the round()
function documentation:
if two multiples are equally close, rounding is done toward the even choice (so, for example, both
round(0.5)
andround(-0.5)
are0
, andround(1.5)
is2
).
Rounding half to the nearest integers always has to break the tie somehow, and different programming languages don’t always agree on how to do this, the IEEE 754 standard defines 5 different methods. Python 3 uses the IEEE 754 default and rounds halves to even, because this method has the advantage that it is free of sign bias and in reasonable distributions of numbers will result in the same average values.
4
solved Why do round() and math.ceil() give different values for negative numbers in Python 3? [duplicate]