While “we all know” that x == y can be problematic, where x and y are floating point values, this question is a bit more specific:
int x = random.Next(SOME_UPPER_LIMIT);
float r = x;
// Is the following ALWAYS true?
r == x
Now, since the range of float of is much larger than that of integers (but the precision is insufficient to uniquely present integers at the edges), it would be nice if responses to this question also addressed which values of x the above can be guaranteed for, if it can be guaranteed at all.
Currently my code is making this assumption (for relatively small values of x) – I would like to make sure that I won’t get bitten 🙂
This will fail with “not equal: 16777217” (cast float -> int):
for (int i = 0; i < int.MaxValue; i++) {
float f = i;
if ((int)f != i) throw new Exception("not equal " + i);
}
This similar code will not fail (only int -> float); however, due to loss in the conversion, there are several floats that can “equal” the same integer, and may represent a silent bug:
for (int i = 0; i < int.MaxValue; i++) {
float f = i;
if (f != i) throw new Exception("not equal " + i);
}
Yes, the comparison will always be true, whatever value the
intis.The
intwill be converted to afloatto do the conversion, and the first conversion tofloatwill always give the same result as the second conversion.Consider:
The values of
yandzwill always be the same. If the conversion loses precision, both conversions will lose the precision in exactly the same way.If you convert the
floatback tointto to the comparison, that’s another matter.Also, note that even if a specific
intvalue converted tofloatalways results in the samefloatvalue, that doesn’t mean that thefloatvalue has to be unique for thatintvalue. There areintvalues where(float)x == (float)(x+1)would betrue.