0

So...I have to check some values if they are equal. But they never were and I knew that they should be, I debugged my application and reached the following conclusion

-2.5f - Mathf.Round(1.1f) * 0.6f - (-3.1f) doest not equal to 0 but instead it's value is -1.192093E-07

Is there a reasonable explanation for this and is there a workaround? I really need the equation in this format.

PS: all values are here hardcoded but they are variables and they have other values too. The problem is when the result should be 0

Here is a line of code: Debug.Log(string.Format("{0} ", -2.5f - Mathf.Round(1.1f) * 0.6f - (-3.1f)));

Using Unity 4.5.1f3 with Monodevelop 4.0.1 on OS X 10.9.5.

CodeSmile
  • 64,284
  • 20
  • 132
  • 217
Daniel Tranca
  • 1,374
  • 3
  • 13
  • 23

1 Answers1

1

Like said in the comments -1.192093E-07 is not infinity it is very close to zero. Notice the minus sign after the "E". The value is .0000001192093.

When you are comparing floating point numbers you should never use ==, because floating point arithmetic is causing that kind of small errors. Instead you can use something like this:

float diff = aValue - bValue;
if(diff < 0.000001f && diff > -0.000001f){

}

It might be good idea to read "What every programmer should know about floating-point arithmetic" for example here.

maZZZu
  • 3,585
  • 2
  • 17
  • 21
  • 1
    And even epsilon comparison isn't a great fix. A good resource to read is http://realtimecollisiondetection.net/blog/?p=89 in that regard. – Bart Dec 07 '14 at 09:03