I am running the following block of code inside a CALLBACK function for a timer.
if (start_value <= end_value)
{
start_value += increment_value;
}
else
{
return 0;
}
all three variables are defined as DOUBLE.
Double start_value = 26.0;
Double end_value = 28.0;
increment_value = 0.1;
when adding the increment_value to start_value, the value of the variable start_value does not simply reflect the expected result of the addition. For example, when start_value is 26.0, after one addition, the value of start_value is 26.10000000001. The trailing 1 causes problems later on in the code, because when the expected result of the comparison is expected to be TRUE, it is evaluated as false because of the trailing 1. Why is this happening?
Eshan, The ==
operator is looking for an exact match, and should be used exclusively for integer comparisons (where exact is possible). So, "why is this happening?" because 26.10000000001 is not equal to 26.1. The difference between the two is sometimes referred to as floating point error.
As long as we are using binary storage of floating point, there will continue to be floating point error. This requires that methods to compare floating points have to be different than when comparing integers. (i.e. for floats, cannot use (x == y) ?
. A quick and dirty alternative to "==" when comparing floats is to do something like this: if(abs(x-y)<epsilon ){//equal}
where epsilon is some small tolerance value like 0.000001
So, try something like this instead:
int main(void)
{
double start_value = 26.0;
double end_value = 28.0;
double increment_value = 0.1;
#define EPSILON 0.000001
while(fabs(start_value-end_value)>EPSILON )
{
printf("not equal\n");
start_value += increment_value;
}
printf("equal\n");
getchar();
}
Note: choose epsilon value to match the neighborhood of significant digits in the comparisons you will do.
There are many other good methods, (and many who will say this is not one of them) but I have used this one for years, and for my purposes, it has worked well.
HERE is a link talking a little about this, and other methods.