Open In App

floor() and ceil() function Python

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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.

Python3




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.



Last Updated : 06 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads