How to perform division correctly?
1 view (last 30 days)
Recenty I've came across this dilemma when dealing with divisions. Actually when performing the division of a number by a product of others number I expect that the following two codes returns the same result:
a = 1 / (x * y);
b = 1 / x / y;
However, comparing the two results, it returns false logical answer.
Besides the error is in the order of esp (10^-16), on the long run it made my simulation numerically unstable.
Which sintax I am expect to use? Anyone experienced something similar?
I leave my own code to reproduce the behavior!
a = 72000 / 12 / ( 1 - 0.3 ^ 2 );
b = 72000 / (12 * ( 1 - 0.3 ^ 2 ));
a == b % false
% eps = 2.2204e-16
rel_err = (a-b)/a; % about -1.38e-16
the cyclist on 23 Jan 2022
Variants of this question come up a lot. It is not a "problem with division", but a consequence of the fact that some decimal numbers cannot be represented exactly in a floating-point representation. I recommend reading through some of the answers to this question.
Here is an example of the inexact representation of a decimal number, using James Tursa's num2strexact function from the File Exchange: