Ceiling Division in Python

To perform ceiling division in Python, you can define your own function and utilize the floor division operator //.

>>> def ceiling_division(x,y):
...     return -1 * (-x // y)
... 
>>> print(ceiling_division(11,3))
4
>>> print(ceiling_division(40,9))
5
>>> print(ceiling_division(1,4))
1
>>> print(ceiling_division(-11,5))
-2
>>> 

You can also utilize the math module ceil() function to perform ceiling division.

>>> import math
>>> print(math.ceil(11/3))
4
>>> print(math.ceil(40/9))
5
>>> print(math.ceil(1/4))
1
>>> print(math.ceil(-11/5))
-2
>>> 

When working with number in Python, the ability to easily perform different calculations is very useful.

One such calculation is ceiling division, or the ceiling of the number you get after dividing two numbers.

In the Python language, we have the // -- > operator for floor division, but there is not a built in function which performs ceiling division.

However, we can create our own function to do ceiling division utilizing the mathematical fact that negative one times the floor of a negative number is equal to the ceiling of a positive number.

Therefore, if we do floor division with two numbers, multiplying the first number by -1 and then taking the resulting number times -1 again, we can get result we want.

Such as ceiling_division function.

def ceiling_division(x,y):
    return -1 * (-x // y)

print(ceiling_division(11,3))
print(ceiling_division(40,9))
print(ceiling_division(1,4))

#Output:
4
5
1

Using math.ceil() to Perform Ceiling Division in Python

Another way that you can do ceiling division in Python is to perform regular division and take the ceiling of the number with the Python math.ceil() function.

The math module ceil() function returns the ceiling of a number.

Ceiling division is simply the ceiling of the result after dividing one number by another.

Therefore, you can do ceiling division by dividing and passing the result to ceil().

Below shows that using the math module ceil() function gives us the same result as our custom function from above.

import math 

print(math.ceil(11/3))
print(math.ceil(40/9))
print(math.ceil(1/4))

#Output:
4
5
1

Hopefully this article has been useful for you to learn how to do ceiling division in your Python code.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章