MATLAB: Matlab won’t return x-x=0, but gives me x-x=1e-18 instead

epsMATLABreturn zerozero

Hi!
I'm doing a linear interpolation to find when Z=0 in my XYZ koordinate system with a for-loop "inside" a while-loop with a condition of dY<1e-4. That is, I want to determine what X and Y will be when Z=0.
Long story short, I'm using this formula:
% f_new = f1 + (z_new - z1)*(f2 - f1)/(z2 - z1);
where during for X, this loop would be:
% x_new = x1 + (0 - z1)*(x2-x1)/(z2-z1);
This works just fine for almost all iterations… But, sometimes during the for Z Matlab doesn't return 0. The formula is simply printed as:
% z_new = z1 + (0 - z1)*(z2 - z1)/(z2 - z1);
which logically should translate to:
% z_new = z1 - z1 = 0;
But here, for some of the iterations it returns that z_new = (+-)3.469446951953614e-18
Maybe this question is a bit messy right now. And I know that a simple solution to this problem is just to simply set Z=0 or even an if-loop like
if abs(Z) < eps
Z = 0;
end
But what I'm really asking is basically: -Why does it do this, and can I prevent it without manually "cheating" by setting z=0?
Thanks, and cheers!

Best Answer

It does it because of finite machine precision, just like any other calculation. I suspect that if you re-implement like so
z_new = z1 + (0 - z1)*((z2 - z1)/(z2 - z1));
then you will get an ideally zero result because this will force ((z2 - z1)/(z2 - z1)) to be computed first and a/a should equal 1 even in finite precision. However, it is bad practice in general to expect computers to perform ideal math. You should make your code robust to numerical residuals like 3.469446951953614e-18.