exercise Floating-point error

0

I have a list of floating point errors and I'm having some difficulty with one of the issues. If anyone can help me, I'm grateful.

For the code below, I need to justify the reason for the error.

int main () {
  double x;
  x = 0.;
  printf("x = %2.13lf\n",x);
  while ( x != 1.0 ) {
    x = x + 0.1;
    printf("x = %2.13lf\n",x);
 }

I think it is related to the rounding of the sum. Is that right or is there something else?

    
asked by anonymous 31.03.2017 / 05:08

1 answer

0

Testing the following code and only changing 2.13 to 2.20

#include  <stdio.h>

int main () {
    int i;
    double x;
    i = 1;
    x = 0.;
    printf("exec %1li",i);
    printf("x = %2.20lf\n",x);
    while ( x != 1.0 ) {
        i++;
        x = x + 0.1;
        printf("exec %1li",i);
        printf("x = %2.20lf\n",x);
    }
}

The output to 2.13 :

exec 1x = 0.0000000000000
exec 2x = 0.1000000000000
exec 3x = 0.2000000000000
exec 4x = 0.3000000000000
exec 5x = 0.4000000000000
exec 6x = 0.5000000000000
exec 7x = 0.6000000000000
exec 8x = 0.7000000000000
exec 9x = 0.8000000000000
exec 10x = 0.9000000000000
exec 11x = 1.0000000000000 // <- Valor a ser considerado, que na notação 10^13 acaba sendo interpretado como 1.0
exec 12x = 1.1000000000000
exec 13x = 1.2000000000000
exec 14x = 1.3000000000000
exec 15x = 1.4000000000000
exec 16x = 1.5000000000000

The output to 2.20 :

exec 1x = 0.00000000000000000000
exec 2x = 0.10000000000000000555
exec 3x = 0.20000000000000001110
exec 4x = 0.30000000000000004441
exec 5x = 0.40000000000000002220
exec 6x = 0.50000000000000000000
exec 7x = 0.59999999999999997780
exec 8x = 0.69999999999999995559
exec 9x = 0.79999999999999993339
exec 10x = 0.89999999999999991118
exec 11x = 0.99999999999999988898 // <- Valor a ser considerado, que na notação 10^13 acaba sendo interpretado como 1.0
exec 12x = 1.09999999999999986677
exec 13x = 1.19999999999999995559
exec 14x = 1.30000000000000004441
exec 15x = 1.40000000000000013323
exec 16x = 1.50000000000000022204

See that for each sum of 0.1 it actually adds 0.10000000000000000555 , where depending on the number of decimal places used to represent the value, the compiler may end up rounding.

Try changing the line from while to while ( x != 0.5 ) { and you will see that the code will not go into infinite loop because the value that was added in this last execution will literally be 0.5 ( 0.50000000000000000000 = 0.5 = 0.5000 ).

I would not say that it is a rounding error, but because 0.1 represents 0.10000000000000000555 for each sum within the while.

    
31.03.2017 / 09:20