Python math.ceil() | Ceiling of a Number

Python supports different modules and packages to do various programming tasks. The module named β€œmath” is used in Python to perform various calculations on data using multiple functions. Some of the functions of the math module are factorial(), floor(), ceil(), exp(), log10(x) etc.

In this article, one of the functions of the β€œmath” module named β€œmath.ceil()” is demonstrated in depth using various examples. The following topics are part of our Python Guide:

So let’s get started!

What is Python β€œmath.ceil()” Function?

The β€œmath.ceil()” function takes numeric data type values like int and floats and rounds up the given number to the nearest integer. The syntax of the β€œmath.ceil()” function is shown below:

math.ceil(numeric expression)

The numeric expression value is required in the β€œmath.ceil()” function to return its ceiling value in an integer.

Note: Boolean value (True and False) can also be passed inside the β€œmath.ceil()” function. They will be utilized as β€œ1 and 0”.

Let’s understand the working of this function with numerous examples given below:

Example 1: Ceiling of a Number Using math.ceil()

In the code given below, the β€œmath.ceil()” function is used to find the ceiling number of different positive and negative float numbers

Code:

import math

print(math.ceil(222.7))
print(math.ceil(992.882))
print(math.ceil(-93.7))
print(math.ceil(-4.8))
print(math.ceil(49))

In the following code:

  • The β€œmath” module is imported in the program using the prefix β€œimport”.
  • The β€œmath.ceil()” function is used with β€œ5” different values in the above code, i.e., two β€œPositive float”, two ”Negative float” and one β€œAbsolute integer” value.
  • The positive value will round up to the nearest integer, and the negative float value will round toward zero.

Output:

The output shows the ceiling value of numeric data.

Example 2: Errors in math.ceil() Function

When the positive or negative infinite value is passed in β€œmath.ceil()” function. The function returns an β€œoverflow” error as an output. Let’s understand via the following code:

Code:

import math

number = math.inf
print(math.ceil(number))

In the following code, the β€œmath.ceil()” function throws an error when the infinite number is passed to it. The β€œmath.inf” expression retrieves a floating point infinity.

Output:

The output shows the β€œoverflow error” of math.ceil() function.

That’s all from this guide!

Conclusion

In Python, the β€œmath.ceil()” function takes positive or negative numeric values as arguments and rounds off the given numbers to the nearest integer. The β€œmath.ceil()” function does not change the absolute integer value. This function gives an error when an infinite or undefined value is passed to it. This article provided all the details regarding the β€œPython math.ceil()” function with numerous examples.