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:
The output will be:
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.
Note that we first import the math package so we can then use the ceil (ceiling) function provided with it. The output will be:
indicating that you will need 3 bags.
math.ceil() with negative numbers
Let us try math.ceil() with negative numbers like so:
we will get:
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:
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:
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.
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!
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.