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

前端 未结 8 1934
刺人心
刺人心 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:19

    As pointed out by other answers, in python they return floats probably because of historical reasons to prevent overflow problems. However, they return integers in python 3.

    >>> import math
    >>> type(math.floor(3.1))
    <class 'int'>
    >>> type(math.ceil(3.1))
    <class 'int'>
    

    You can find more information in PEP 3141.

    0 讨论(0)
  • 2020-12-04 15:22

    Because the range for floats is greater than that of integers -- returning an integer could overflow

    0 讨论(0)
  • 2020-12-04 15:24

    Before Python 2.4, an integer couldn't hold the full range of truncated real numbers.

    http://docs.python.org/whatsnew/2.4.html#pep-237-unifying-long-integers-and-integers

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-04 15:30

    Because python's math library is a thin wrapper around the C math library which returns floats.

    0 讨论(0)
  • 2020-12-04 15:38

    Maybe because other languages do this as well, so it is generally-accepted behavior. (For good reasons, as shown in the other answers)

    0 讨论(0)
提交回复
热议问题