Why do Python's math.ceil() and math.floor() operations return floats instead of integers?
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Industries in Orbit Looping
--
Chapters
00:00 Question
01:01 Accepted answer (Score 106)
01:45 Answer 2 (Score 112)
02:13 Answer 3 (Score 20)
02:28 Answer 4 (Score 18)
03:31 Thank you
--
Full question
https://stackoverflow.com/questions/8582...
Question links:
[docs]: http://docs.python.org/library/math.html...
[@jcollado]: https://stackoverflow.com/a/8582845/1656...
Answer 1 links:
[PEP 3141]: http://www.python.org/dev/peps/pep-3141/...
Answer 3 links:
[IEEE 754]: https://en.wikipedia.org/wiki/IEEE_float...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #math
#avk47
ANSWER 1
Score 117
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.
ACCEPTED ANSWER
Score 107
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.
ANSWER 3
Score 20
Because python's math library is a thin wrapper around the C math library which returns floats.
ANSWER 4
Score 5
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