Hi all,
I'm using an Arduino Mega (ATmega2560) and I'm facing a very weird issue when I compare two float numbers, which seem to have the same value.
My code is below. Please don't mind those conversions I made in the code. It is used in my actual application where I first detected this problem.
char a[]={'0','0','0','0','0','0','0','3'};
char d[]={'0','0','0','0','0','0','0','5'};
float b=0;
volatile float c[]={0.01, 0.01, 0.01};
volatile long int p=299;
volatile long int k=499;
volatile float t=0;
void setup() {
Serial.begin(9600);
b=atof(a);
t=p*c[0];
Serial.print("b=");
Serial.println(b,3);
Serial.print("t=");
Serial.println(t,3);
Serial.print("diff1=");
Serial.println(b-t,3);
if (b-t<c[0])
{
Serial.println("NOT Correct!!!");
}
else
{
Serial.println("Correct!!!");
}
b=atof(d);
t=k*c[0];
Serial.print("b=");
Serial.println(b,3);
Serial.print("t=");
Serial.println(t,3);
Serial.print("diff2=");
Serial.println(b-t,3);
if (b-t<c[0])
{
Serial.println("NOT Correct!!!");
}
else
{
Serial.println("Correct!!!");
}
}
void loop()
{
}
As you can see the value b-t is equal to 0.01, and the value of c[0] is also 0.01, however the first "if" statement returns "NOT Correct!!!", meaning that the value of b-t is less than c[0].
On the second option of comparing I changed the value from 3 to 5. And in this case again the value b-t is equal to 0.01, and the value of c[0] is also 0.01, and the second "if" statement returns "Correct!!!".
Can anyone tell what is the reason of this behavior?
Thanks in advance.