Why do Python's math.ceil() and math.floor() operations return floats instead of integers?

前端 未结 8 1939
刺人心
刺人心 2020-12-04 15:11

Can someone explain this (straight from the docs- emphasis mine):

math.ceil(x) Return the ceiling of x as a float, the small

8条回答
  •  一整个雨季
    2020-12-04 15:27

    The source of your confusion is evident in your comment:

    The whole point of ceil/floor operations is to convert floats to integers!

    The point of the ceil and floor operations is to round floating-point data to integral values. Not to do a type conversion. Users who need to get integer values can do an explicit conversion following the operation.

    Note that it would not be possible to implement a round to integral value as trivially if all you had available were a ceil or float operation that returned an integer. You would need to first check that the input is within the representable integer range, then call the function; you would need to handle NaN and infinities in a separate code path.

    Additionally, you must have versions of ceil and floor which return floating-point numbers if you want to conform to IEEE 754.

提交回复
热议问题