floor() and ceil() function Python
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:
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:
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.
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.
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.
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.
Please Login to comment...