Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing floating-point 0

If foo is of float type, is the following expression valid/recommended?

(0.0f == foo * float(0))

Will it have the expected (mathematical) value regardless of foo's value?

Does the C++ standard defines the behavior or is it implementation specific?

like image 327
CsTamas Avatar asked Oct 12 '10 13:10

CsTamas


People also ask

Is the floating point comparison similar to integer comparison?

The floating point comparison is not similar to the integer comparison. To compare two floating point values, we have to consider the precision in to the comparison. For example, if two numbers are 3.1428 and 3.1415, then they are same up to the precision 0.01, but after that, like 0.001 they are not same.

What does floating point mean in math?

Then we run afoul of the "floating" part, which means there is no guarantee of which numbers can be represented. So while we might easily be able to represent "1.0, -1.0, 0.1, -0.1" as we get to larger numbers we start to see approximations - or we should, except we often hide them by truncating the numbers for display.

Is there a one size fits all floating-point comparison?

There is no "one size fits all" floating-point comparison. You have to think about the semantics of your variables, the acceptable range of values, and the magnitude of error introduced by your computations.

Is there a lot of confusion about floating-point numbers?

There is a lot of confusion about floating-point numbers and a lot of bad advice going around. IEEE-754 floating-point numbers are a complex beast [1], and comparing them is not always easy, but in this post, we will take a look at different approaches and their tradeoffs.


1 Answers

Well, first off it isn't really a matter of the C++ standard. Rather what is at issue is your floating-point model standard (most likely IEEE).

For IEEE floats, that is probably safe, as float(0) should result in the same number as 0.0f, and that multiplied by any other number should also be 0.0f.

What isn't really safe is doing other floating point ops (eg: adds and subtracts with non-whole numbers) and checking them against 0.0f.

like image 138
T.E.D. Avatar answered Oct 11 '22 05:10

T.E.D.