c - Labwindows strange behavior when adding DOUBLE numbers -


this question has answer here:

i running following block of code inside callback function timer.

if (start_value <= end_value)  {    start_value += increment_value; } else {    return 0; } 

all 3 variables defined double.

double start_value = 26.0; double end_value = 28.0; increment_value = 0.1; 

when adding increment_value start_value, value of variable start_value not reflect expected result of addition. example, when start_value 26.0, after 1 addition, value of start_value 26.10000000001. trailing 1 causes problems later on in code, because when expected result of comparison expected true, evaluated false because of trailing 1. why happening?

eshan, == operator looking exact match, , should used exclusively integer comparisons (where exact possible). so, "why happening?" because 26.10000000001 not equal 26.1. difference between 2 referred floating point error.

as long using binary storage of floating point, there continue floating point error. requires methods compare floating points have different when comparing integers. (i.e. floats, cannot use (x == y) ?. quick , dirty alternative "==" when comparing floats this: if(abs(x-y)<epsilon ){//equal} epsilon small tolerance value 0.000001

so, try 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 match neighborhood of significant digits in comparisons do.

there many other methods, (and many not 1 of them) have used 1 years, , purposes, has worked well.
here link talking little this, , other methods.


Comments

Popular posts from this blog

c++ - CryptStringToBinary API behavior -

c++ - Correct method for redrawing a layered window -

java.util.scanner - How to read and add only numbers to array from a text file -