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.
Answer from jcollado on Stack OverflowWhy do Python's math.ceil() and math.floor() operations return floats instead of integers? - Stack Overflow
what is the difference between using math.ceil and round for rounding the decimal ?
how to use math.ceil in both python 2 and 3 to get the int number?
Python math.ceil BUG in leetcode
Videos
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.
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.
in python 2, math.ceil returns float, but I need it returns int, and I also want my code run correctly in python2 and 3. Currently , I define my own ceil function like this
def ceil(float_num):
import sys
if sys.version[0] == '2':
from math import ceil as ceiling
return int(ceiling(float_num))
elif sys.version[0] == '3':
from math import ceil
return ceil(float_num)I am just wondering is there any better solution? just like from __future__ import devision?