Kodeclik Blog
math.ceil() in Python
Let us suppose you have 18 books that you would like to store into bags. Let us suppose each bag can store 8 books. We can try to find how many bags it would take to store the given books. Let us write a simple Python program for this problem:
num_books = 18
bag_capacity = 8
print(num_books/bag_capacity)
The output will be:
2.25
meaning we need 2.25 bags. But there is no such thing as a fractional bag! You are going to need 3 bags where 2 of them will be full (8 books each, for a total of 16 books) and the third bag will have the remaining 2 books.
To accomplish this in Python, you can use the handy math.ceil() function. It takes a number as input and rounds it up to the nearest integer. Here is how that works.
import math
num_books = 18
bag_capacity = 8
print(math.ceil(num_books/bag_capacity))
Note that we first import the math package so we can then use the ceil (ceiling) function provided with it. The output will be:
2
indicating that you will need 3 bags.
math.ceil() with negative numbers
Let us try math.ceil() with negative numbers like so:
import math
print(math.ceil(-1.4))
we will get:
-1
Recall that we always round up to the next highest integer. So the next highest integer to -1.4 is -1. To confirm, let us try:
import math
print(math.ceil(-1.9))
Now -1.9 is really close to -2, i.e., closer to -2 than to -1. But the output of the above program will still be:
-1
because math.ceil() always rounds up (see above figure). The formal way of saying this is that math.ceil() always returns the smallest integer value greater than the input number.
So, to summarize, the math.ceil() method is a built-in function for the math module; it rounds a number up to the next highest integer and returns the result. It takes a single parameter that is to be rounded. If the number passed as a parameter is an integer, then the same number is returned. If the number passed as a parameter is a float, then the next highest integer is returned.
If you liked this blogpost, see our blogpost on the math.floor() function which is complementary to the math.ceil() function. Also learn about the closely related math.trunc() function.
Finally, checkout the related math.isclose() function in Python.
Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.