C# Promblem .

can someone explain this ?

float lavaG = lava.material.GetFloat(“_IllumInt”);

print(lavaG) //prints" -1.5 "

if(lavaG==-1.5f)print(“Yahoo”) //prints nothing…

However :

if(lavaG<-1.5f)print(“Yahoo”) //prints “Yahoo”

What the hell ?..

Here is the script ( it supposed to animate material illimination from -1 to -1.5 :

if(Mathf.Abs(lavaG)>1.5000001)print (“Yahoo”) //prints yahoo too ? wtf is this ?

This is a result of floating point rounding errors.
The value may display “-1.5”, but internally the actual value is just below that value, perhaps “-1.500000001”.

So the actual value is less than “-1.5” AND of course greater than Abs(-1.5) which would be comparing against “1.500000001”.

I always try to avoid comparing exact floating point values, I always use “>=”, or “<=” if it applies.

Or, build a custom function that takes a range, and if the compared value is ± that range, it is considered “equal”.

// Compare two floats for equality, within an acceptable (optional) range
bool FloatEquals(float value1, float value2, float range=0.00001) {
    return Mathf.Abs(value1 - value2) < range ? true : false;
}

// Usage:
if (FloatEquals(lavaG, -1.5, 0.01)) // Override default range
if (FloatEquals(lavaG, -1.5)) // Use default range

Or use Mathf.Approximately if you don’t mind having an Epsilon.

@KeslsoMRK: Ha, I guess it’s good to know what functions already exist!
Epsilon? Never even heard of that, until I googled it.

@Sahkan: Ya, use Mathf.Approximately then, since it does what I did (basically) using a built in function.