the Floating-point error

c, floating-point, floating-point-conversion

Solution

Because floating point math is not associative:

i.e. `(a + b) + c` is not necessarily equal to `a + (b + c)`

Problem

``` #include <stdio.h> int main() { int n; while ( scanf( "%d", &n ) != EOF ) { double sum = 0,k; if( n > 5000000 || n<=0 ) //the judgment of the arrange break; for ( int i = 1; i <= n; i++ ) { k = (double) 1 / i; sum += k; } /* for ( int i = n; i > 0; i-- ) { k = 1 / (double)i; sum += k; } */ printf("%.12lf\n", sum); } return 0; } ``` Why in the different loop I get the different answer. Is there a float-error? When I input `5000000` the sum is `16.002164235299` but as I use the other loop of for (notation part) I get the sum `16.002164235300`.

Original source