MonoDevelop Xamarin Source Analysis warning about float comparison?
Is it mandatory to use something like Mathf.Approximately instead of comparing floats against 0?
When enabling "Source Analysis" in MonoDevelop Xamarin, which seems to be necessary if you want the old refactoring functionality back, it complaints about statements like:
if (controller.velocity.sqrMagnitude != 0)
with the following warning:
Warning: comparison of floating point numbers can be unequal...
I never had issues with this kind of comparison in Unity and I am not a programmer in a way that I know about precisions in computer arithmetic.
Answer by NoseKills · Feb 14, 2016 at 10:38 AM
Depends on the situation. If you are trying to avoid a divide by zero with this check, it's totally OK like this.
But if you are slowing down velocity with some sort of a formula which should eventually give the result 0 based on common math, you cannot trust that it will hit exactly 0.
Answer by Owen-Reynolds · Feb 14, 2016 at 08:38 PM
Using == with floats is always legal. You're never required to use Mathf.Approx just to avoid syntax errors. I safely use ==0 all the time.
My guess is that nothing has actually changed. Xamarin just feels like giving you that warning now, and didn't feel like it before. It's really a warning for beginners. Not useless, but if you know anything about floats, an annoying waste of text.
But nosekills comments is correct. If you haven't, see what's been written here in UA about floats, or just read about float math anywhere. For example, x=1.0f, then a loop x=x-0.1f; will often not hit 0 exactly.