Can someone explain this (straight from the docs- emphasis mine):
math.ceil(x) Return the ceiling of x as a float, the small
The range of floating point numbers usually exceeds the range of integers. By returning a floating point value, the functions can return a sensible value for input values that lie outside the representable range of integers.
Consider: If floor()
returned an integer, what should floor(1.0e30)
return?
Now, while Python's integers are now arbitrary precision, it wasn't always this way. The standard library functions are thin wrappers around the equivalent C library functions.
This is a very interesting question! As a float requires some bits to store the exponent (=bits_for_exponent
) any floating point number greater than 2**(float_size - bits_for_exponent)
will always be an integral value! At the other extreme a float with a negative exponent will give one of 1
, 0
or -1
. This makes the discussion of integer range versus float range moot because these functions will simply return the original number whenever the number is outside the range of the integer type. The python functions are wrappers of the C
function and so this is really a deficiency of the C
functions where they should have returned an integer and forced the programer to do the range/NaN
/Inf
check before calling ceil/floor.
Thus the logical answer is the only time these functions are useful they would return a value within integer range and so the fact they return a float is a mistake and you are very smart for realizing this!