The Wayback Machine - https://web.archive.org/web/20240926213559/https://www.geeksforgeeks.org/floor-ceil-function-python/
Open In App

floor() and ceil() function Python

Last Updated : 20 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The floor() function:

floor() method in Python returns the floor of x i.e., the largest integer not greater than x. 

Syntax:
import math
math.floor(x)

Parameter:
x-numeric expression.

Returns:
largest integer not greater than x.

Below is the Python implementation of floor() method: 

Python
# Python program to demonstrate the use of floor() method

# This will import math module
import math

# prints the ceil using floor() method
print "math.floor(-23.11) : ", math.floor(-23.11)
print "math.floor(300.16) : ", math.floor(300.16)
print "math.floor(300.72) : ", math.floor(300.72)

Output: 

math.floor(-23.11) :  -24.0
math.floor(300.16) : 300.0
math.floor(300.72) : 300.0

The ceil() Function:

The method ceil(x) in Python returns a ceiling value of x i.e., the smallest integer greater than or equal to x.

Syntax: 
import math
math.ceil(x)

Parameter:
x:This is a numeric expression.

Returns:
Smallest integer not less than x.


Below is the Python implementation of ceil() method: 

Python
# Python program to demonstrate the use of ceil() method

# This will import math module
import math   

# prints the ceil using ceil() method
print "math.ceil(-23.11) : ", math.ceil(-23.11)
print "math.ceil(300.16) : ", math.ceil(300.16)
print "math.ceil(300.72) : ", math.ceil(300.72)

Output: 

math.ceil(-23.11) :  -23.0
math.ceil(300.16) : 301.0
math.ceil(300.72) : 301.0

Using integer division and addition:

In this approach, x // 1 is used to obtain the integer part of x, which is equivalent to math.floor(x). To obtain the ceiling of x, we add 1 to the integer part of x.

Python
x = 4.5

# Round x down to the nearest integer
rounded_down = x // 1
print(rounded_down)  # Output: 4

# Round x up to the nearest integer
rounded_up = x // 1 + 1
print(rounded_up)  # Output: 5

Output
4.0
5.0

Approach:
The code takes a float number x and uses floor division to round it down to the nearest integer. It then prints the result. It then uses floor division and addition to round x up to the nearest integer, and prints the result.

Time Complexity:
The time complexity of the round() function is constant, which means that the time complexity of the alternative code is also constant. The time complexity of the original code is also constant, as it uses only a few simple arithmetic operations.

Space Complexity:
The space complexity of both the original code and the alternative code is constant, as they both use only a few variables to store the input and the result.

floor() and ceil() function Python – FAQs

What does floor() function do?

The floor() function in Python, typically found in the math module, returns the largest integer less than or equal to a given number. It effectively rounds down a floating-point number to the nearest integer.

import math
# Example of using floor()
result = math.floor(3.7)
print(result) # Output: 3

What is the difference between floor and Ceil?

The key difference between floor and ceil functions lies in their rounding behavior:

  • floor: Rounds down to the nearest integer.
  • ceil: Rounds up to the nearest integer.

For example:

import math
# Examples of floor() and ceil()
print(math.floor(3.7)) # Output: 3
print(math.ceil(3.7)) # Output: 4

What is the floor function in NumPy?

In NumPy, the floor function, part of the numpy module, operates element-wise on an array and returns the largest integer less than or equal to each element.

import numpy as np
# Example of floor function in NumPy
arr = np.array([3.7, 2.1, -1.5, 0.6])
result = np.floor(arr)
print(result) # Output: [ 3. 2. -2. 0.]

What is the Ceil function in Python?

The ceil() function in Python, also found in the math module, returns the smallest integer greater than or equal to a given number.

import math
# Example of using ceil()
result = math.ceil(3.7)
print(result) # Output: 4

How to do ceil in Python without math?

You can achieve ceiling rounding without using the math module by leveraging arithmetic operations:

# Ceiling function without math module
def ceil(x):
return -int(-x // 1)
# Example usage:
result = ceil(3.7)
print(result) # Output: 4

How to find the floor of a number in Python?

To find the floor of a number in Python, use the math.floor() function from the math module:

import math
# Example of finding the floor of a number
result = math.floor(3.7)
print(result) # Output: 3


Similar Reads

Pandas Series dt.ceil | Ceil DateTime To Specified Frequency
The dt.ceil() method performs ceil operation on the data to the specified frequency. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-12-31 08:45', '2019-1-1 12:30', '2008-02-2 10:30', '2010-1-1 09:25', '2019-12-31 00:00']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index = idx sr = pd.to_datetime(sr) result = sr.dt.ceil(fre
2 min read
Ceil and floor of the dataframe in Pandas Python – Round up and Truncate
In this article, we will discuss getting the ceil and floor values of the Pandas Dataframe. First, Let's create a dataframe. Example: C/C++ Code # importing pandas and numpy import pandas as pd import numpy as np # Creating a DataFrame df = pd.DataFrame({'Student Name': ['Anuj', 'Ajay', 'Vivek', 'suraj', 'tanishq', 'vishal'], 'Marks': [55.3, 82.76,
2 min read
Python | math.ceil() function
In Python, math module contains a number of mathematical operations, which can be performed with ease using the module. math.ceil() function returns the smallest integral value greater than the number. If number is already integer, same number is returned. Syntax: math.ceil(x) Parameter: x: This is a numeric expression. Returns: Smallest integer no
1 min read
Python | Pandas DatetimeIndex.ceil()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas DatetimeIndex.ceil() function ceil the data to the specified frequency. The function takes the target frequency as input. It retu
2 min read
Python | Pandas TimedeltaIndex.ceil
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas TimedeltaIndex.ceil() function ceil the index of the TimedeltaIndex object to the specified freq. The function takes the frequenc
2 min read
Python | Pandas Timestamp.ceil
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Timestamp.ceil() function return a new Timestamp ceiled to this resolution. The function takes the desired time series frequency
2 min read
Python | Pandas Timedelta.ceil()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Timedelta is a subclass of datetime.timedelta, and behaves in a similar manner. It is the pandas equivalent of python’s datetime.timedel
1 min read
Python - PyTorch ceil() method
PyTorch torch.ceil() method returns a new tensor having the ceil value of the elements of input, Which is the smallest integer larger than or equal to each element. Syntax: torch.ceil(inp, out=None) Arguments inp: This is input tensor. out: The output tensor. Return: It returns a Tensor. Let's see this concept with the help of few examples: Example
1 min read
numpy.ceil() in Python
The numpy.ceil() is a mathematical function that returns the ceil of the elements of array. The ceil of the scalar x is the smallest integer i, such that i >= x Syntax : numpy.ceil(x[, out]) = ufunc ‘ceil’) Parameters : a : [array_like] Input array Return : The ceil of each element with float data-type. Code #1 : Working # Python program explain
2 min read
Ceil in a Binary Search Tree Python
In a Binary Search Tree (BST), the ceiling of a given value is the smallest element in the tree that is greater than or equal to the given value. Finding the ceiling in a BST can be a useful operation when working with ordered data. In this article, we will explore how to find the ceiling in a Binary Search Tree using Python. Binary Search Tree Ove
3 min read
Python | math.floor() function
In Python, math module contains a number of mathematical operations, which can be performed with ease using the module. math.floor() function returns the largest integer not greater than x. If number is already integer, same number is returned. Syntax: math.floor(x) Parameter: x: This is a numeric expression. Returns: largest integer not greater th
1 min read
Check the equality of integer division and math.floor() of Regular division in Python
For large quotients, floor division (//) doesn't seem to be necessarily equal to the floor of regular division (math.floor(a/b)) Examples: Input : 269792703866060742 // 3 Output : 89930901288686914 Input : math.floor(269792703866060742 / 3) Output : 89930901288686912 In the above examples, the output for floor division(//) is 89930901288686914 and
2 min read
Python | Pandas DatetimeIndex.floor()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas DatetimeIndex.floor() function floor the data to the specified frequency. The function takes the target frequency as input. It re
2 min read
Python | Pandas TimedeltaIndex.floor
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas TimedeltaIndex.floor() function floor all the values in the given TimedeltaIndex object to the specified frequency. Syntax : Time
2 min read
Python | Pandas Timestamp.floor
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Timestamp.floor() function return a new Timestamp floored to this resolution. The function takes the desired time series frequenc
2 min read
Python | Pandas Timedelta.floor()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Timedelta is a subclass of datetime.timedelta, and behaves in a similar manner. It is the pandas equivalent of python’s datetime.timedel
1 min read
Python - PyTorch floor() method
PyTorch torch.floor() method returns a new tensor which is floor of the elements of input, the largest integer less than or equal to each element. Syntax: torch.floor(input, out=None) Arguments input: This is input tensor. out: The output tensor. Return: It returns a Tensor. Let's see this concept with the help of few examples: Example 1: # Importi
1 min read
numpy.floor() in Python
The numpy.floor) is a mathematical function that returns the floor of the elements of array. The floor of the scalar x is the largest integer i, such that i <= x. Syntax : numpy.floor(x[, out]) = ufunc ‘floor’) Parameters : a : [array_like] Input array Return : The floor of each element. Code #1 : Working # Python program explaining # floor() fu
2 min read
How to get the floor, ceiling and truncated values of the elements of a numpy array?
In this article, let's discuss how to get the floor, ceiling, and truncated values of the elements of a Numpy array. First, we need to import the NumPy library to use all the functions available in it. This can be done with this import statement: import numpy as np Getting the floor value The greatest integer that is less than or equal to x where x
3 min read
Floor division in SQLAlchemy
In this article, we will see how to perform floor division in SQLAlchemy against a PostgreSQL database in python. Floor division is performed in different methods using different functions. Such kinds of mathematical operations are database-dependent. In PostgreSQL, floor division is performed using a function called div(). In SQLAlchemy, generic f
2 min read
Pandas Series dt.floor() | Round DateTime Values to Nearest Frequency
The dt.floor() method performs floor operation on the data to the specified frequency. This is useful when we want to round down the DateTime data to a specific frequency level, such as hourly (‘H’), daily (‘D’), monthly (‘M’), etc. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-12-31 08:45', '2019-1-1 12:30', '2008-02-2 10:30', '2010
2 min read
Wand function() function in Python
function() function is similar to evaluate function. In function() function pixel channels can be manipulated by applies a multi-argument function to pixel channels. Following are the list of FUNCTION_TYPES in Wand: 'undefined''arcsin''arctan''polynomial''sinusoid' Syntax : wand.image.function(function, arguments, channel) Parameters : ParameterInp
1 min read
Python - Call function from another function
Prerequisite: Functions in Python In Python, any written function can be called by another function. Note that this could be the most elegant way of breaking a problem into chunks of small problems. In this article, we will learn how can we call a defined function from another function with the help of multiple examples.  What is Calling a Function
5 min read
Returning a function from a function - Python
Functions in Python are first-class objects. First-class objects in a language are handled uniformly throughout. They may be stored in data structures, passed as arguments, or used in control structures. Properties of first-class functions: A function is an instance of the Object type.You can store the function in a variable.You can pass the functi
4 min read
Python math.sqrt() function | Find Square Root in Python
sqrt() function returns square root of any number. It is an inbuilt function in Python programming language. In this article, we will learn more about the Python Program to Find the Square Root. sqrt() Function We can calculate square root in Python using the sqrt() function from the math module. In this example, we are calculating the square root
3 min read
How to calculate and plot the derivative of a function using matplotlib and python?
In this article, we are going to learn how to calculate and plot the derivative of a function using Matplotlib in Python. In our higher standard in school, we all have studied derivatives in the mathematics syllabus of calculus and we know that calculus is a fundamental branch that deals with the study of rates of change and slopes of curves. The d
4 min read
wxPython - GetField() function function in wx.StatusBar
In this article we are going to learn about GetField() function associated to the wx.GetField() class of wxPython. GetField() function Returns the wx.StatusBarPane representing the n-th field. Only one parameter is required, that is, field number in status bar. Syntax: wx.StatusBar.GetField(self, n) Parameters: Parameter Input Type Description n in
1 min read
Map function and Lambda expression in Python to replace characters
Given a string S, c1 and c2. Replace character c1 with c2 and c2 with c1. Examples: Input : str = 'grrksfoegrrks' c1 = e, c2 = r Output : geeksforgeeks Input : str = 'ratul' c1 = t, c2 = h Output : rahul We have an existing solution for this problem in C++. Please refer to Replace a character c1 with c2 and c2 with c1 in a string S. We can solve th
2 min read
Python | Find the Number Occurring Odd Number of Times using Lambda expression and reduce function
Given an array of positive integers. All numbers occur even number of times except one number which occurs odd number of times. Find the number in O(n) time & constant space. Examples: Input : [1, 2, 3, 2, 3, 1, 3] Output : 3 We have existing solution for this problem please refer Find the Number Occurring Odd Number of Times link. we will solv
1 min read
Intersection of two arrays in Python ( Lambda expression and filter function )
Given two arrays, find their intersection. Examples: Input: arr1[] = [1, 3, 4, 5, 7] arr2[] = [2, 3, 5, 6] Output: Intersection : [3, 5] We have existing solution for this problem please refer Intersection of two arrays link. We will solve this problem quickly in python using Lambda expression and filter() function. Implementation: C/C++ Code # Fun
1 min read
Practice Tags :