I have a piece of code that repetitively decreases a variable which starts at 1. After two iterations, the result is inexact, which came as a surprise.
The effective process can be shown by the following two lines:
>> (1 - 0.1) - 0.9
0
>> (1 - 0.05 - 0.05) - 0.9
-1.110223024625157e-16
The result in the second case is not zero, in both Matlab and Octave.
Similarly, the following C code shows the problem:
#include <stdio.h>
void main () {
double x1, x2;
x1=1-0.05-0.05;
x2=1-0.1;
printf("x1 exact:%d, x2 exact:%d\n", x1==0.9, x2==0.9);
}
Compiled with gcc version 4.7.0 on Intel Xeon(R) CPU E5-2680, the result is
x1 exact:0, x2 exact:1
show that the first calculation is inexact while the second is exact.
I can overcome this in C by using long double (suffix "L" for all literals, and the variables declared as long double). This leaves me somewhat confused: I assumed the inexact result can be explained by the fact that 0.05 does not have an exact representation in base 2; but using long double does not change this fact... so why is the result different?
What I really want is a way to overcome it in Matlab. Any ideas?
Interestingly, MS Excel result for this same calculation is exact in both cases.