Why the following simple calculation is NOT consistent

4 views (last 30 days)
Here are simple multiplication and division of scalars but the results are not consistent. What is causing this and how to make it consistent?
A1 = 0.025; E1 = 70e9; L1 = 1;
A2 = 0.05; E2 = 100e9; L2 = 1.5;
A3 = 0.075; E3 = 50e9; L3 = 2;
k1 = 3*A1*E1/L1;
k2 = 2*A2*E2/L2;
k3 = A3*E3/L3;
k01 = 3*E1*A1/L1;
k02 = 2*E2*A2/L2;
k03 = E3*A3/L3;
% D1, D2, D3 must be "0"
D1 = k01-k1 % ??? WHY: D1 ~=0
D1 = -9.5367e-07
D2 = k02-k2 % = 0
D2 = 0
D3 = k03-k3 % = 0
D3 = 0
% BUT D1 is NOT "0"

Walter Roberson on 4 Oct 2021
Floating point arithmetic is not commutative.
You can see the effect with even simple calculations
format long g
example = 29/7*7
example =
29
fprintf('%.999g\n', example)
29.000000000000003552713678800500929355621337890625
example - 29
ans =
3.5527136788005e-15
Remember that binary floating point does not use decimal internally.
Using decimal would not solve the problems: consider that in decimal, to 10 decimal places
1/3 == 0.3333333333
0.3333333333 * 3 = 0.9999999999
1 - 0.9999999999 = 0.0000000001
Every finite-representation number base has the same problem when it comes to dividing by a value that is relatively prime to the base. Base 60 arithmetic, for example, would be happy with fractions 1/2, 1/3, 1/4, 1/5, 1/6, 1/10, 1/12 -- but would have the same kind of problems for 1/7 .
Sulaymon Eshkabilov on 4 Oct 2021
Thanks Walter!
Well detailed explanation. These simple calc errors would create a significant calculation errors when dealing with large system matrices like global stiffness matrix calcs. They work consistently in MS Excel though :).

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!