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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With