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.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)