The floor function is the part of the math module that returns the floor of a given number (x) which is the largest integer number less than or equal to the x. For example:
floor(5.5) = 5
floor(-3.9) = 4
This is how floor() function is used in Python:
The floor function takes an argument that is a number for what you want to get the floor value.
An example of using floor with integer numbers
In this example, I used the floor() function four times. Different floating point numbers are given including a negative number.
#Floor() function demo import math flr1 = math.floor(1.6) flr2 = math.floor(1.3) flr3 = math.floor(-5.6) flr4 = math.floor(105.4) print ("Floor of 1.6 = " ,flr1) print ("Floor of 1.3 = " ,flr2) print ("Floor of -5.6 = " ,flr3) print ("Floor of 105.4 = " ,flr4)
The result of the above code is:
The first two numbers are 1.6 and 1.3 and both resulted in 1.
What is ceil function?
Just like the floor() function, you have to import the math module to use this function.
To demonstrate the usage of the ceil() function, I used the same numbers as for floor() function to get the ceil.
See the output and difference by comparing with the above result:
#ceil() function demo import math ceil1 = math.ceil(1.6) ceil2 = math.ceil(1.3) ceil3 = math.ceil(-5.6) ceil4 = math.ceil(105.4) print ("Ceil of 1.6 = " ,ceil1) print ("Ceil of 1.3 = " ,ceil2) print ("Ceil of -5.6 = " ,ceil3) print ("Ceil of 105.4 = " ,ceil4)
The result:
Ceil of 1.6 = 2
Ceil of 1.3 = 2
Ceil of -5.6 = -5
Ceil of 105.4 = 106
You can see, unlike the floor() function, ceil for 1.6 and 1.3 resulted in 2.
Getting the floor of list items
If you have a list of items that are floating point numbers and you want to get the floor then one of the ways is using the lambda function with floor() and getting the floor.
The code below uses a list of a few items that contain float and int items:
#Floor() function demo with list import math floor_lst = [10.5, 25.7, 35.47, -25.7, -50.5, 100, 105.9] flr_res = map(lambda F: (math.floor(F)), floor_lst) print("The Floor of list items: ", list(flr_res))
The result:
Similarly, you may get the ceil of list items for the same list as in above example:
#Ceil function demo with list import math ceil_lst = [10.5, 25.7, 35.47, -25.7, -50.5, 100, 105.9] ceil_res = map(lambda C: (math.ceil(C)), ceil_lst) print("The ceil of list items: ", list(ceil_res))
The output: