Hi all,
I have a mystery that I am unable to solve. Given the follow code:
float otherValue = 0.00002f;
float value1 = 1.0f + otherValue;
float value2 = 1.0f;
float value3 = 1.0f + otherValue;
Debug.Log(value1 <= value2 + otherValue);
Debug.Log(value1 <= value3);
The output is:
false
true
I would expect the output to be:
true
true
You can put this in the start function of any script if you want to try it.
My question is, why is this the case?
I ran into this problem today and I can work around it by doing something like what is done with value3 above, but I would like to understand what’s causing this problem so I can prepare for it in the future.
It’s because of the way floating point numbers are stored in computers. In short, you can’t count on floating point numbers being equal even if they should be mathematically. If you want to know exactly why, you can read about it here.
The solution is checking if numbers are very close to being equal, using Mathf.Approximately() for instance.
Hi Thomas, thanks for the response. Yes, it is a floating point issue due to the way the run time interprets the non-variable code vs variable code. I just found a detailed answer here if anyone is interested. I thought I understood floating point precision but of course there is always more to the story
There is a little bit more detail in my question on StackOverflow
http://stackoverflow.com/questions/32233974/why-is-this-simple-c-sharp-equality-check-inconsistent