Floats Not Working

So I have this script that’s meant to detect the amount of rotations the drone base does, and what it’s meant to do is increase the “rotamount” float variable by one when the rotspin float variable reaches 180 and it’s multiplied by the total rotamount total.

  if (rotspin == -180 * rotamount || rotspin == -180 && rotamount == 0)
        {
            rotamount += 1;
            Debug.Log("Rotate");
        }

The part that says “|| rotspin == -180 && rotamount == 0” is there to make sure that it will increase even if the rotamount is zero. However, it seems to only making the rotamount variable increase after the rotspin variable reaches 180 and keep the rotamount variable at one. How can I fix this and/or change it to work better then it did before?

Well, floats do work, they probably just don’t work as you currently understand them. Namely, due to floating point inaccuracy, floats will rarely land on whole numbers.

You haven’t shown us how you’re handling rotspin but it’s likely that it’s not producing the values you expect.

1 Like

Comparing floats using == is bound to fail in most cases, because 0.00000…0001 is not zero (gross oversimplification, but you get the idea). Most IDEs will even show a warning if you try this.

Always use an epsilon when comparing floats, or Unity’s Mathf.Approximately.

This is even more true when one side of == is not actually a float. In the original post I see number -180 which is an integer, not a float. If you write 0.5, it’s a double, not a float. Conversion from float to double can produce extra inaccuracy.
What’s even worse about it is that debugger and print-formatting often approximate floats, so you actually see the same numbers, yet when you compare them, you get the “not equals”.

So, to summarize: if you compare floats using ==, !=, <, >, <=, >=, you are probably making a mistake.

2 Likes

Yes, I’ve been bitten by this one a lot in the past: when formatting floats to strings for printing, most often they’re rounded/truncated so the value you see is not their actual value. Be extra careful, OP!

Don’t do this ^ ^ ^ … Here’s why:

Floating (float) point imprecision:

Never test floating point (float) quantities for equality / inequality. Here’s why:

https://starmanta.gitbooks.io/unitytipsredux/content/floating-point.html

https://discussions.unity.com/t/851400/4

https://discussions.unity.com/t/843503/4