Why do Python's math.ceil() and math.floor() operations return floats instead of integers?
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Orient Looping
--
Chapters
00:00 Why Do Python'S Math.Ceil() And Math.Floor() Operations Return Floats Instead Of Integers?
00:39 Answer 1 Score 117
00:58 Accepted Answer Score 107
01:31 Answer 3 Score 20
01:42 Answer 4 Score 18
02:33 Answer 5 Score 5
02:44 Thank you
--
Full question
https://stackoverflow.com/questions/8582...
--
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