Python ceil

The Python ceil function is used to return the smallest integer value, which is greater than or equal to the specified expression or a specific number. In short, we can say the ceil() function rounds upwards. Unlike previous versions, the latest Python version returns an integer value as the output of the math.ceil function. For example, the ceiling value of 2.23 is 3.

Python ceil function syntax

The standard syntax of the math ceil function is

math.ceil(number);

The above syntax uses the math and dot to call the ceil() method. However, instead of importing the math module, if we import the ceil() function, the syntax does not need math.

from math import ceil

ceil(number);

The Python ceil() function accepts numerical values, such as floating-point numbers. The ceil() method returns the smallest integer value greater than or equal to the given number as output.

  • If the number argument is a positive or negative number, it returns the ceiling value.
  • If it is not a number, the math method returns TypeError.
  • If the given number is not a finite (inf) or not a number (NaN), the ceil() function returns a ValueError.

How does the Python ceil function work?

The following image kind of table that is the visual representation of the Python ceil() function in action. The arrow shows how the ceil() function moves upwards for positive and negative values.

-∞….-3-2-10123….
————-> ————->

For a positive number, the ceil() function returns the next closest number towards ∞ because it is greater than or equal to the given number. For example, ∞ > … > 3 > 2 > 1.

For a negative number, the Python ceil() function returns the next closest number towards 0 because it is greater than or equal to the given number. For example, (-1 > -2 > -3 > … >-∞.

NOTE: The math library is a standard Python module that contains various functions to perform mathematical operations. To utilize the ceil() function inside a program, we must import the math library.

Python ceil Function Example

This Function allows you to find the smallest integer value that is greater than or equal to the numeric values. In this ceil function example, we find the ceiling values of different data types and display the output.

import math

Tup = (10.98, 20.26, 30.05, -40.95 , 50.45) # Tuple Declaration
Lis = [-10.98, 32.65, -39.59, -42.15 , 35.97] # List Declaration

print('Value of Positive Number = %.2f' %math.ceil(10))
print('Value of Negative Number = %.2f' %math.ceil(-15))

print('Value of Tuple Item = %.2f' %math.ceil(Tup[2]))
print('Value of List Item = %.2f' %math.ceil(Lis[2]))

print("The Value of 'PI' after the Ceil function is: ", math.ceil(math.pi))

print('Value of Multiple Number = %.2f' %math.ceil(10 + 20 - 40.65))

print('Value of String Number = ', math.ceil('Python'))
Python math ceil Function Example

Analysis

  1. Within the first two statements, we used the Python ceil() function directly on both positive and negative integers and returned an integer.
  2. Next two statements, we used it on Tuple and List items. If you observe the above Python screenshot, the Math function is working them perfectly.
  3. In the next statement, we tried this directly on multiple values.
  4. Last, we tried the math Function on the String value, and it returns TypeError.

Python ceil() function on Positive numbers

As we mentioned earlier, the ceil() function returns the smallest integer value that is greater than or equal to the given number. Unlike the round() function, ceil() does not matter how many decimal values there are, and it does not follow the 5 rule of decimal precision.

In the following example, the ceil() function returns the same value (3) for both 2.1 and 2.7 because 3 is the smallest integer value greater than or equal to both 2.1 and 2.7. Similarly, the last statement has 5.12987, and the ceil() function won’t care about the number of decimal points; it simply returns the next integer value.

import math
a = 2.1
print(math.ceil(a))

b = 2.7
print(math.ceil(b))

c = 5.12987
print(math.ceil(c))

Result

3
3
6

One real-time example is calculating freight cost. When it comes to weight by cost proportion, we must use the ceil() function to round the weight to the next closest integer value.

import math
itemWeight = 7.8
costPerKG = 5

total = math.ceil(itemWeight) * costPerKG
print(total)
40

TIP: To round downwards, use the floor function.

Python ceil() function with negative numbers

As we mentioned earlier, when we pass the negative numbers to the ceil() function, it returns the next closest number moving towards 0.

When the user sees the -3.9 value, users thought the ceil() function returns -4, which is the most commonly confused one.

  • -3 > -3.9 > -4. Remember, -3 is the smallest integer greater than -3.9, and the ceil() returns the smallest integer greater than or equal to the given number. On the other hand, -4 is smaller than -3.9.
  • Similarly, -10 is greater than -10.2178. Here, -10 > -10.2178 > -11.
import math
a = -3.9
print(math.ceil(a))

b = -10.2178
print(math.ceil(b))

Result

-3
-10

Ceiling integer values

In the following example, we pass an integer value to the Python ceil() function to check the result. As we all know, there are no decimals to find the nearest integer, so the ceil() returns the same integer as the output.

import math
n = 25
print(math.ceil(n))
25

Ceiling 0

The following example shows the ceiling value of 0, so pass zero as the ceil() function argument, and it returns 0 as the output.

import math
print(math.ceil(0))
0

Using the Python ceil() function on the user input

This example allows the user to enter their own floating-point number and then uses the ceil() function to return the next closest integer value.

import math
n = float(input("Enter Number = "))
print(math.ceil(n))

Result

Enter Number = 12.987
13

Parenthesis in calculations

When working with the Python math ceil() function, we must be careful with the mathematical calculations. Remember, parenthesis plays vital role in the order of execution.

Here, the first statement finds the next closest integer to 24.6789 (25) and 13.25 (14). Next, it performs the addition, and the total becomes 39. The second print() statement adds 24.6789 and 13.25 becomes 37.9289. Next, the math ceil() function rounds to the next value, that is 38.

import math
n = 24.6789
m = 13.25

print(math.ceil(n) + math.ceil(m))
print(math.ceil(n + m))

Result

39

38

Python ceil() function on a list of floating-point numbers

Lists are very common, and this section shows how to use the ceil() function on a list of numeric values (floating-point numbers).

The following example uses a list comprehension to iterate over the list of floating-point numbers. On each iteration, the ceil() function is applied to the list item.

import math
n = [10.98, 20.5678, 30.86, 40.45678]

result = [math.ceil(i) for i in n]
print(result)
[11, 21, 31, 41]

We can also use the map() function to apply the ceil() function on each list item. However, we must use the list() method to convert the map object to a list. Please replace the line of code below in the above program.

[result = [math.ceil(i) for i in n]

with the line below.

result = list(map(math.ceil, n))

NOTE: We can also use the for loop with/without range to iterate over these list items and apply the ceil() function on them.

Ceiling list of Positive and negative numbers

The following example uses a combination of positive and negative floating-point numbers as the list items. Here, the Python math ceil() function is applied to both positive and negative numbers in a given list.

import math
n = [10.12, -25.56, -45.6, 65.9, 70.9]

result = [math.ceil(i) for i in n]
print(result)
[11, -25, -45, 66, 71]

Use the Python ceil() function to round the price list

We can use the ceil() function to round the values in the price list to the nearest integer value. In the example below, we declared a list of three electronic product prices and used the ceil() function to round the mobile price to the nearest value.

import math
prices = [999.67, 1299.89, 1499.12]

result = [math.ceil(n) for n in prices]
print(result)
[1000, 1300, 1500]

Use the Python ceil() function on aggregated values

When working with a list of prices or any financial data, we use different aggregated functions to perform operations. For example, the sum of sales, average price, total orders by postal code, etc. This aggregated data may not be polished because prices include decimals, and the aggregated data also comes with a decimal value.

In such a scenario, use the ceil() function to round the aggregated result obtained from sum() and other functions. In the following example, we used the sum() function to find the list total and applied the ceil() function to round its value.

import math
n = [10.8, 48.7, 30.6, 40.45]

total = sum(n)

print(total)
print(math.ceil(total))

Result

130.55
131

Similarly, use the other functions to see the results. For instance, replace the line below

total = sum(n)

with the sum() and len() functions.

total = sum(n) / len(n)

Using the Python ceil() function with Tuples

We can also use the math ceil() function to round the tuple values. Imagine we are running a shipping company where the price is calculated based on the item’s weight. In such a scenario, we can use the ceil() function to round the item weight to the next possible integer. For example, if the item excess of 0.01, it will land in the next price bracket.

import math
weight = (2.1, 3.4, 5.03, 7.6)

result = tuple(math.ceil(n) for n in weight)
print(result)
(3, 4, 6, 8)

NOTE: We can also apply the same ceil() function logic on nested tuples to round them.

Using Python ceil() function with sets

We should be more conscious when working with the ceil() and set combination. As we know, sets won’t allow any duplicates, and if found, they are removed automatically.

If the ceil() function result of the items in a set is unique, the result is the ceiling integer of all elements. However, if there are no unique, the result is different.

In the following example, we declared a set of four elements. After applying the ceil() function, the result set has only three elements. Here, both 24.29 and 24.985 return the same result, 25, so the duplicates are removed and only one is kept.

import math
dup = {10.9, 24.29, 50.78, 24.985}

result = set(math.ceil(n) for n in dup)
print(result)
{25, 11, 51}

Using Python ceil() function with dictionaries

The following example accepts the users and their monthly bandwidth usage as the dictionary key and items. Next, the ceil() function reads the dictionary key-value pair and rounds each user’s bandwidth usage to the nearest number.

import math
montly_Usage = {"user1": 100.56, "user2": 80.9, "user3": 250.67}

result = {users: math.ceil(bandwidth)
for users, bandwidth in montly_Usage.items()}
print(result)
{'user1': 101, 'user2': 81, 'user3': 251}

Similarly, we can calculate the usage cost for each user. For example, the hosting company charges $3 for 1 GB of bandwidth. We can use the ceil() function to calculate the monthly bill and round it to the nearest value.

import math
montly_Usage = {"user1": 100.56, "user2": 80.9, "user3": 250.67}

billing = {users: math.ceil(bandwidth * 3)
for users, bandwidth in montly_Usage.items()}
print(billing)
{'user1': 302, 'user2': 243, 'user3': 753}

Difference between Python ceil() and floor()

Although both ceil() and floor() functions are part of the math module and accept a single numeric value as an argument, they differ in result.

ceil()floor()
The ceil function returns the smallest integer value that is greater than or equal to the given number.The floor function returns the largest integer value that is less than or equal to the given number.
It is a part of the math library.It is a part of the math library.
It rounds the given value upward.It rounds the given value downward.
ceil(10.4) = 11floor(10.4) = 10

Difference between Python ceil() and int()

When working with floating-point numbers, both the int() and ceil() functions return an integer value as the output. So, most people think they are the same. However, there is a difference in the result.

  • int(): In simple words, the int() function always truncates toward zero. So, the integer value is always moving towards zero.
  • ceil(): For positive numbers, it moves away from zero, and for negative numbers, it moves towards zero.

Positive Numbers

For positive numbers, the Python ceil() function returns the next closest integer value. On the other hand, the int() function truncates decimal values and prints the integer part as the output.

import math
n = 50.387
print(int(n))
print(math.ceil(n))

Result

50
51

Negative Numbers

For negative numbers, both int() and ceil() functions return the smallest integer number greater than or equal to the given number.

import math
n = -17.387
print(int(n))
print(math.ceil(n))

Result

-17
-17

Difference between Python ceil() and round()

The following table illustrates the difference between the math ceil() function and the round() method.

ceil()round()
The ceil() function is a part of the math module, and we must import the math library to use it.The round() is a regular built-in function, so we don’t have to import anything to use it.
math.ceil(x)round(x, n)
The ceil() function accepts a single argument and returns the next closest integer.The round() function rounds the number based on the second argument. It also follows the famous 5 rules.
Return value is an integer.It returns a float value.
math.ceil(10.456) = 11round(10.8796, 0) = 11.0 round(10.8796, 1) = 10.9
round(10.8796, 2) = 10.88  
import math

n = 24.6789

print(math.ceil(n))
print(round(n))
print(round(n, 1))
print(round(n, 2))
print(round(n, 3))

Result

25
25
24.7
24.68
24.679

Python ceil division

As we all know, there is a built-in // operator to get the floor division result, or we can use the floor function. However, there is no separate operator in Python to perform ceiling division. We must use the ceil() function on the result set to get the result.

Here, the quotient of n and m is 5.738. If we use the // operator, the result becomes 5, but when we use the ceil() function, the output is 6.

import math

n = 24.1
m = 4.2

res = n/m
print(res)
print(math.ceil(res))

Result

5.738095238095238

6

Using the Python math.ceil () function in a NumPy array

In the NumPy module, there is a built-in ceil() function that operates exclusively on ndarrays. We can also use the math ceil() function on these arrays, but the performance is very slow and requires an iteration process.

In the following example, we applied the NumPy ceil() function directly on the array, and it returns the next closest value. However, we need a for loop or list comprehension to iterate over the array items and then apply the math,ceil() function on each item.

import numpy as np
import math

n = [2.5, 3.5, 7.23, 4.5, 8.67]
a = np.array(n)
print(np.ceil(a))

result = [math.ceil(i) for i in a]
print(result)

Result

[3. 4. 8. 5. 9.]
[3, 4, 8, 5, 9]

NOTE: The NumPy ceil() method returns a floating-point number, so we must convert it to an integer. On the other hand, the math.ceil() returns an integer value.

Python math ceil() function in Pandas DataFrame

Apart from the built-in numpy ceil() function, we can use the math.ceil() function on a dataframe. However, the performance of the math ceil() method is very slow, so use it on small datasets or mixed types.

import pandas as pd
import math

prices = {"Phones": ["iPhone", 'Samsung', 'Pixel'],
"values": [999.21, 899.56, 759.4]}
data = pd.DataFrame(prices)

data["ceiling"] = data["values"].apply(math.ceil)
print(data)

Result

    Phones  values  ceiling
0 iPhone 999.21     1000
1  Samsung  899.56      900
2    Pixel  759.40      760

Always use numpy ceil() for faster and more reliable results on pandas datasets. So, replace the line below in the above program

data["ceiling"] = data["values"].apply(math.ceil)

with

data["ceiling"] = np.ceil(data["values"])

Common Errors of the Python ceil() function

The following are some common errors we face while working with math.ceil() method.

NameError: Missing math module

If we use the ceil() function without importing the math module, the program will throw NameError. So, always add import math at the program’s starting position.

n = 24.6789
print(math.ceil(n))
NameError: name 'math' is not defined. Did you forget to import 'math'?

Using Non-numeric arguments

The ceil() function accepts only numeric values as its parameter. If you pass other data types, it will throw TypeError. Here, we pass a string containing numbers. However, the ceil() returns a TypeError.

import math
print(math.ceil("10.234"))
TypeError: must be real number, not str

Using the None argument

The ceil() function won’t allow any None value as its parameter, and passing None throws a TypeError.

import math
print(math.ceil(None))
TypeError: must be real number, not NoneType

Passing NaN parameter

If you pass a NaN (not a number) argument to the ceil() function, it will throw a ValueError.

import math
print(math.ceil(float('nan')))
ValueError: cannot convert float NaN to integer

Using Inf as a parameter

Similar to NaN, the positive and negative Inf (infinite) values, as the ceil() function argument, throw ValueError.

import math
print(math.ceil(float('inf')))
OverflowError: cannot convert float infinity to integer

Without using Python ceil() function (Custom Code)

There are many approaches to finding the ceiling value of a given positive or negative number. We can use either the built-in math ceil function or create a custom function with advanced options.

In the following example, we wrote a custom code that computes the ceiling without using the ceil() function. Here, we utilized the int() method inside the If Else and added one for the positive numbers.

import math
def customCeil(n):
m = int(n)
return m if n == m else (m + 1 if n > 0 else m)

p = 10.34
ne = -20.67
print(customCeil(p))
print(customCeil(ne))

Result

10
-20

Apart from the above, we can use a simple short version with the negative operand. The following function also finds the ceiling value of positive and negative numbers without the math ceil() function.

def customCeil(n):
    return -int(-n)