Floor. With math.floor we reduce a number so that the fractional part is removed. Floor() will make all numbers smaller. Negative values will become more negative.
number = 78.6# This will not work.
result = floor(number)Traceback (most recent call last):
File "C:\programs\file.py", line 5, in <module>
result = floor(number)
NameError: name 'floor' is not defined
Negative floors. With negative numbers, math.floor has the same logical result as with positive ones. Numbers are always reduced. Negative numbers will become more negative.
import math
# Use math.floor on a negative number.
result = math.floor(-1.1)
print(result)
result = math.floor(-1.9)
print(result)-2
-2
Benchmark, floor dictionary. I wanted to test whether a dictionary lookup could be faster than a math.floor call. I found math.floor is fast—much faster than calling get().
Version 1 This version of the code uses math.floor to get the floor of each number.
Version 2 Here we look up a value in a dictionary to get a cached floor value for a number.
Result Using a dictionary to memoize (cache) the result of math.floor is a big slow down. Just use math.floor directly.
import time, math
# Floor dictionary.
floor_dict = {100.5: 100}
print(time.time())
# Version 1: use math.floor.
for i in range(0, 100000000):
y = 100.5
z = math.floor(y)
if z != 100:
print(z)
break
print(time.time())
# Version 2: use dictionary lookup, get method.
for i in range(0, 100000000):
y = 100.5
z = floor_dict.get(y)
if z != 100:
print(z)
break
print(time.time())1454633830.142
1454633830.727 math.floor = 0.59 s
1454633839.844 floor_dict.get = 9.12 s
PyPy3 used
A review. In Python 3 we find many built-in functions like abs and round. With floor, though, we have to use the math module with an import statement.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Apr 27, 2023 (edit).