What is the ceiling function in Python, and how does it work?
The ceiling function in Python is found in the
math
library and it’s method name is
ceil()
which takes a sole numeric parameter.
To use the ceiling function in Python you will need to import the math library, like so:
>>> import math
>>> math.ceil(1.6)
2
>>> math.ceil(-2.1)
-2
As you can see from the above Python REPL code the output produces the greatest integer.
If the
ceil()
function is not obvious on what it does, you could rename the function on import to be more explicit by awarding it it’s proper name – in other words renaming it so that the function is called
ceiling()
.
If you did want to rename the ceiling function you would need to modify the initial import line to read:
>>> from math import ceil as ceiling
>>> ceiling(1.6)
2
>>> ceiling(-2.1)
2
What Does
floor()
Do?
What if you wanted the number to round down if it was negative? In other words you wanted the value of -2.2 to round down to -3.
The opposing function to
ceil()
is
floor()
. This finds the nearest minimum integer number to the value passed in and is the same process for using
ceil()
, as demonstrated below:
>>> import math
>>> math.floor(1.99)
1
>>> math.floor(-2.1)
-3
As you can see from the above output with using the
floor()
method the value returned is the smallest integer if the number can be found between two integers (otherwise if the value is an integer or can be converted to one, like 1.0 can be converted to 1, it retains that value).
Combining the two methods means you can round up positive numbers and round down negative numbers simply by wrapping it all in a one line if statement like so:
>>> import math
>>> def my_round(n):
... return math.ceil(n) if n >= 0 else math.floor(n)
...
>>> my_round(1.99)
1
>>> my_round(-2.1)
-3
As you can see the custom function I’ve written serves the basic purpose of rounding up positive numbers and rounding down negative numbers.
Summary
The Python ceiling function is found in the math library and has the method name
ceil().
It takes a number as it’s sole parameter and rounds numbers up.
It’s opposing function is found in the same math library and is known as the
floor()
method and this rounds numbers down.
If the
ceil()
method is confusing to remember when you are typing your code you may opt to rename the function on import to
ceiling()
by changing the import line of the math library to
from math import ceil as ceiling
.