C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Rounding: Floor does not round upon the value 100.9. Instead it always reduces the number to be less.
Python program that uses math.floor
import math
# Some numbers to take floors of.
value0 = 100
value1 = 100.1
value2 = 100.5
value3 = 100.9
# Take floor of number.
floor0 = math.floor(value0)
print(value0, ":", floor0)
# Take other floors.
print(value1, ":", math.floor(value1))
print(value2, ":", math.floor(value2))
print(value3, ":", math.floor(value3))
Output
100 : 100
100.1 : 100
100.5 : 100
100.9 : 100
Python program that causes NameError
number = 78.6
# This will not work.
result = floor(number)
Output
Traceback (most recent call last):
File "C:\programs\file.py", line 5, in <module>
result = floor(number)
NameError: name 'floor' is not defined
Python program that uses math.floor on negative numbers
import math
# Use math.floor on a negative number.
result = math.floor(-1.1)
print(result)
result = math.floor(-1.9)
print(result)
Output
-2
-2
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.
Python program that benchmarks math.floor, dictionary
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())
Output
1454633830.142
1454633830.727 math.floor = 0.59 s
1454633839.844 floor_dict.get = 9.12 s
PyPy3 used