I have a simple function, a – b + c, whose value depends on the order of addition/subtraction:
clear; clc;
a = -1.0;
b = 0.9;
c = 0.9;
d = a - b + c;
e = a - (b - c);
f = (a - b) + c;
g = a + c - b;
disp(['d = ',num2str(d,'%1.38f')])
disp(['e = ',num2str(e,'%1.38f')])
disp(['f = ',num2str(f,'%1.38f')])
disp(['g = ',num2str(g,'%1.38f')])
disp(['d - e = ',num2str(d-e,'%1.38f')])
disp(['d - f = ',num2str(d-f,'%1.38f')])
disp(['d - g = ',num2str(d-g,'%1.38f')])
Command Window
d = -0.99999999999999988897769753748434595764
e = -1.00000000000000000000000000000000000000
f = -0.99999999999999988897769753748434595764
g = -1.00000000000000000000000000000000000000
d - e = 0.00000000000000011102230246251565404236
d - f = 0.00000000000000000000000000000000000000
d - g = 0.00000000000000011102230246251565404236
On paper, d = e = f = g = 1. However, MATLAB reports that d ~= e, d = f, and d ~= g. Here are some other observations:
- If instead a = 1.0, then MATLAB reports d = e = f = 1 ~= g.
- If instead b = c = 0.8, then MATLAB reports d = e = f = g = 1 (as desired).
What is happening and why?
I tried changing the parameter values to see if the problem persists.
New contributor
user25234289 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.