You will spot a difference when using floats:
>>> 1000.5//1
1000.0
>>> floor(1000.5)
1000
floor returns an integer. For most cases 1000 and 1000.0 are equivalent, but not always.
python - math.floor(N) vs N // 1 - Stack Overflow
Why do Python's math.ceil() and math.floor() operations return floats instead of integers? - Stack Overflow
Am I understanding this Floor part of the math module correctly?
floor() function isn't working
Videos
You will spot a difference when using floats:
>>> 1000.5//1
1000.0
>>> floor(1000.5)
1000
floor returns an integer. For most cases 1000 and 1000.0 are equivalent, but not always.
math.floor(N)returns an int, andN // 1returns a float.>>> type(math.floor(-4.4)) <class 'int'> >>> type((-4.4) // 1) <class 'float'>Because of this
floor(nan)will raise ValueError whilenan // 1returns NaN (similar for ±inf.)>>> math.floor(math.nan) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: cannot convert float NaN to integer >>> math.nan // 1 nan
I don't think there are other differences when N is a float, since x//y is defined as ⌊x/y⌋.
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.
So I am up to the Practice makes Perfect portion of Code Academies python course, and I am onto the question where they ask you to check for an integer without using type(int).
My answer ended up being:
import math
def is_int(x):
if math.floor(x) == 0:
return True
else:
return False
print is_int(2.0)
print is_int(2.3)
However this came up with an error and I found out I had to instead write it like this:
import math
def is_int(x):
if math.floor(x) - x == 0:
return True
else:
return False
print is_int(2.0)
print is_int(2.3)
Is my understanding correct in the extra (- x) is so that when the value subtracts from itself it becomes 0 by default thus is always an integer number unlike the float?