------ Please jump to the last update -----------
I have found a bug (in my code) and I am struggling to find correct understanding of it.
It all boils down to this specific example taken from the immediate window while debugging:
x
0.00023569075
dx
-0.000235702712
x+dx+1f < 1f
true
(float) (x+dx+1f) < 1f
false
x and dx are both of type float. So why is the boolean value different when I do a cast?
In the actual code i had:
x+=dx
if( x+1f < 1f) // Add a one to truncate really small negative values (originally testing x < 0)
{
// do actions accordingly
// Later doing
x+=1; // Where x<1 has to be true, therefore we have to get rid of really small negatives where x+=1 will give x==1 as true and x<1 false.
}
but I am now trying with the cast
x+=dx;
if( (float)( x+1f) < 1f) // Add a one to truncate really small negative values (originally testing x < 0)
{
// do actions accordingly
// Later doing
x+=1; // Where x<1 has to be true, therefore we have to get rid of really small negatives where x+=1 will give x==1 as true and x<1 false.
}
Visual studio says that the cast is redundant but it DO get a false positve without it as de immediate window also told me when:
x+dx+1f < 1f
true
I am currently running my code to see if I get the bug again with the cast and I will update as soon as I get convinced either way.
In the meanwhile I hope someone can sort out whats going on here? Can I expect the Cast to do something?
Update - Variables My variables x and dx are components of a Vector2 (Xna/monogame). So in the code you should read
Vector2 coord; // the x (and y) components are floats.
Vector2 ds;
coord.X // where it says x
ds.X // where it says dx
I thought this would not matter, but maybe it does.
Update 2 - Drop the above example
Seeing that the cast did change the outcome I made this simple demonstration
class Program
{
static void Main(string[] args)
{
float a = -2.98023224E-08f; // Just a small negative number i picked...
Console.WriteLine(((a + 1f) < 1f) ? "true" : "false"); //true
Console.WriteLine(((float)(a + 1f) < 1f) ? "true":"false"); //false
// Visual Studio Community 2015 marks the above cast as redundant
// but its clearly something fishy going on!
Console.Read();
}
}
So, why does this cast change the result when even VS says it is redundant?