- Home /
Float Comparison is not working
I'm having trouble with comparison of 2 float values in a C# script after having exhausted what I have seen as possible answers. Here is the code that assigns the value to the first float every FixedUpdate():
currentTime += Time.deltaTime;
currentTime = Mathf.Round(currentTime*100f)/100f;
The other float is assigned a float value from another method. Its value never changes. I've tried the "==" comparison as well as Mathf.Approxmately(). I've also tried changing each of the hard-coded values from simple numbers (100) to decimals (100.0) and appending "f" to designate them as floats. I've tried many combinations of the above 3 in conjunction with the different comparison options but the comparison is NEVER evaluated as true.
Am I missing something terribly obvious?
Answer by Mike 3 · Nov 22, 2010 at 02:18 AM
You really shouldn't ever compare floats with ==, as soon as you do any maths with them they'll be different internally, even if they look similar
What you can do is make a simple function to check for equality within a tolerance, e.g.
function IsApproximately(a : float, b : float)
//lets you skip the tolerance to use a sane default value
{
return IsApproximately(a, b, 0.02);
}
function IsApproximately(a : float, b : float, tolerance : float)
{
return Mathf.Abs(a - b) < tolerance;
}
ALternatively, when you create your conditional statements, use the greater/less than operators, e.g:
if (myVal > -0.05 || myVal < 0.05) { /* do something */ }
The reason Mathf.Approximately isn't always too useful is that it's basically the function above, with Mathf.epsilon as the tolerance, which is the smallest possible float value, so it's not likely to be within it after a few sums
@$$anonymous$$ike You are wrong about $$anonymous$$athf.Approximately. You can look at code in Reflector - tolerance is a maximum of: 0.000001 $$anonymous$$ax(a,b) -- most cases , or 8 epsilon. It'a a good approximation for most game development tasks.
@$$anonymous$$ike: No, epsilon is not the smallest possible float value. It's the smallest positive float value that is greater than zero.
Ah, I see what happened - in 2.6 they used float.Epsilon for approximately, which was ridiculous, but changed it to a much saner calculation for 3
Great answer. As of today (Unity v5.4.2f2) I also just had the same issue with an "epsilon size" float variable, testing against "<". if ([variable of 4.482269E-05 value] < [0.05f const]) { / does not ever happen... / } A little counter-intuitive as I supposed 0.05f is a number big enough to be stored (kinda) precisely (at least againts a 10^-5 epsilon), but this was a good lesson :)
Answer by zoon · Nov 22, 2010 at 09:01 AM
First of all, you can get current time much easier:
currentTime = Mathf.Round(Time.time);
Second: you should never compare time and constant with ==
, always use <=
or =>
Example:
const float kickHim = 5f;
...
if (Time.time >= kickHim)
{
DoKickHim()
}
Your answer
