InterviewSolution
| 1. |
Python's math module has ceil() and floor() division functions. What is the difference? |
|
Answer» Python has a built-in round() function that rounds given number to NEAREST integer. >>> round(3.33) 3 >>> round(3.65) 4Sometimes, you may need a largest integer smaller than given number, or a smallest integer, that is larger than given number. This is where floor() and ceil() functions in math module are used. As the name suggests, ceil() stands for ceiling. It returns nearest integer greater than given number or numeric expression. >>> import math >>> math.ceil(3.33) 4 >>> math.ceil(3.65) 4The floor() function on the other HAND returns integer that is smaller than given number or numeric expression indicating that given number is larger than a certain fraction from the RESULTING integer. >>> import math >>> math.floor(3.33) 3 >>> math.floor(3.65) 3The floor() function shows a peculiar behaviour when the number or numeric expression is negative. In such case, the result is floored away from 0. >>> math.floor(-3.65) -4 |
|