mljrg
mljrg

Reputation: 4620

Compare rounded floats in Python

I know that in general two floats must be compared like abs(f1-f2) < 1e-6, but if they are rounded before comparison is it safe to compare their rounded values for equality in Python?

if round(f1,5)==round(f2,5):
    print "equal"
else
    print "unequal"

Thanks

Upvotes: 3

Views: 6757

Answers (2)

Eric Postpischil
Eric Postpischil

Reputation: 224313

First, it is not necessary to compare two floats with an error tolerance as you suggest. The relationship between two floating-point numbers depends on how they were derived, and that varies hugely between applications. There is no uniform answer for this.

Second, the equality-comparison of two rounded values will return true if and only if the values are equal. Allowing any sort of tolerance to get an “approximately equals” function will have no effect (if the tolerance is less than the rounding distance).

However, rounding values in floating-point is problematic because small errors may move a value from one side of a rounding point to another. For example, consider rounding f1 to the nearest integer, where f1 is some value you have computed with floating-point operations that included rounding errors. (Rounding errors occur when a mathematical result of an operation is not exactly representable, so the computer has to round it to the nearest representable result.) If f1 is very near, say, 2.5, what should it round to? Obviously, if it is less than 2.5, it will round to 2, and if it is greater, it will round to 3. But suppose the ideal value for f1, calculated with exact mathematics, is slightly greater than 2.5, but the computed value is slightly less than 2.5, due to rounding errors. Then f1 will round to 2, but we would have preferred it to round to 3.

At the same time, suppose you have an f2 that correctly rounds to 3. If you compare the rounded f1 to the rounded f2, they will be unequal.

So, after you have rounded numbers, it is too late to consider what errors might have been in them; that information is gone. Comparing numbers after they are rounded cannot tell you whether the exact mathematical results would have been close to each other before rounding.

The solution for this depends on your particular application and how the numbers are calculated. There is no general solution.

Upvotes: 4

AlexErofeev
AlexErofeev

Reputation: 161

No. As said in documentation,

The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68.

So the answer is still floating-point number and we can't have any guarantee on its exact value.

There are examples where round() returns number, that can't be represented exactly as floating-point numbers and result still needs to use epsilon for proper comparison ( round() in Python doesn't seem to be rounding properly , for example)

Upvotes: 1

Related Questions