Felipe D.
Felipe D.

Reputation: 1271

When rounding a decimal/float to an integer, what's the difference between using round, floor or ceil in python?

When trying to round a decimal point value (a float) to an integer, what is the actual difference between the round, math.floor and math.ceil functions in python?

Upvotes: 0

Views: 627

Answers (1)

Felipe D.
Felipe D.

Reputation: 1271

Quick answer with examples

The difference is how they truncate and round the input.

round rounds towards the closest integer (breaking ties by choosing even numbers), math.floor rounds towards -inf and math.ceil rounds towards +inf.

It's also worth noting that round(x,0) returns a float while round(x), floor(x) and ceil(x) return integers.

Here are a couple of examples:

Input (x) round(x) math.floor(x) math.ceil(x)
1.4 1 1 2
1.5 2 1 2
1.6 2 1 2
-1.4 -1 -2 -1
-1.5 -2 -2 -1
-1.6 -2 -2 -1
2.5 2 2 3
3.5 4 3 4
4.5 4 4 5
-2.5 -2 -3 -2
-3.5 -4 -4 -3
-4.5 -4 -5 -4

Note how round(-1.4) yields -1 while math.floor(-1.4) yields -2.

Also note how round(2.5) yields 2 while round(3.5) yields 4.

Longer answer

round

The longer explanation is that when you use round(x) or round(x,0), Python uses a method called round half to even. The method finds the closest integer. In cases where the distance is the same to both larger and smaller integers, as the name suggests, the algorithm breaks the tie by choosing the closest even number. That's why round(2.5) yields 2: because 2.5 is equally distant to 2 and 3, and in cases with two equally distant choices, the algorithm picks the even choice.

The Python documentation can be found here and here. This SO question is also worth checking out.

math.floor and math.ceil

On the other hand, math.floor and math.ceil explicitly take the closest integer that is smaller and larger than the input values, respectively. That's why it's said that they round "towards -/+ inf".

Take the following example: -1.4. In this case, the closest integer that is smaller than or equal to the input (i.e., closest to -inf) is -2. That's why math.floor(-1.4) yields -2.0. Similarly, the closest integer that is larger than or equal to the input (i.e., closest to +inf) is -1, which is why math.ceil(-1.4) yields -1.

Here are the links to Python's documentation for floor and ceil

(Credit to @MarkDickinson for pointing out a few mistakes in my original answer!)

Upvotes: 2

Related Questions