Testing the following code and only by 2.13
for 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 exit 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 exit 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 at each sum of 0.1
is actually added 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 of while
for while ( x != 0.5 ) {
and you will see that the code will not go into an infinite loop because the value that was added on that last run will literally be 0.5
(0.50000000000000000000
= 0.5
= 0.5000
).
I wouldn’t say it’s a rounding error, but rather due to 0.1
represent 0.10000000000000000555
to each sum within the while.
Syntax error: also missing
}
to close themain
– MarceloBoni