Python

math

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))100 : 100
100.1 : 100
100.5 : 100
100.9 : 100

Error

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

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

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())1454633830.142
1454633830.727 math.floor = 0.59 s
1454633839.844 floor_dict.get = 9.12 s
PyPy3 used

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).