Python 3 – Number ceil() Method
Python has a rich set of powerful built-in functions that make it easier for programmers to work with numbers. One such built-in function is the ceil()
method, which is part of the math
module. The ceil()
method is used to find the smallest integer that is greater than, or equal to, a given number. In this article, we will explore the use of the ceil()
function in Python.
Syntax
The syntax of the ceil()
function is as follows:
import math
math.ceil(x)
Here, x
is the number for which we want to find the smallest integer greater than or equal to it.
Example 1 – Finding the smallest integer
Let’s take an example to understand the use of the ceil()
function:
import math
x = 2.5
print(math.ceil(x))
Output:
3
In this example, we have passed the value 2.5
to the ceil()
function, which returns the smallest integer greater than or equal to 2.5
, which is 3
.
Example 2 – Finding the smallest integer in a list
The ceil()
function can also be used to find the smallest integer greater than or equal to all elements in a list:
import math
my_list = [1.1, 2.2, 3.3, 4.4, 5.5]
for i in my_list:
print(math.ceil(i))
Output:
2
3
4
5
6
In this example, we have created a list of float values and used a loop to pass each element of the list to the ceil()
function. The function returns the smallest integer greater than or equal to each element in the list.
Example 3 – Using ceil()
in math calculations
The ceil()
function can also be used in conjunction with other mathematical operations. Let’s take an example:
import math
x = 3.5
y = 2.2
z = 1.1
result = math.ceil(x/y)*z
print(result)
Output:
2.2
In this example, we have used the ceil()
function to find the smallest integer greater than or equal to the result of the division of x
and y
. The result of this operation is then multiplied by z
to get the final result.
Example 4 – Using ceil()
with negative numbers
The ceil()
function also works with negative numbers. Let’s take an example:
import math
x = -2.5
print(math.ceil(x))
Output:
-2
In this example, we have passed the value -2.5
to the ceil()
function, which returns the smallest integer greater than or equal to -2.5
, which is -2
.
Conclusion
In this article, we have explored the ceil()
function in Python. We have discussed its syntax and provided several examples of how it can be used to find the smallest integer greater than or equal to a given number or element in a list. We have also seen how it can be used in conjunction with other mathematical operations, and how it works with negative numbers. The ceil()
function is a useful tool for programmers who need to work with numbers in Python.