How to perform division correctly?

14 次查看(过去 30 天)
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
  1 个评论
the cyclist
the cyclist 2022-1-23
Not directly related to what you are seeing here, but also be aware that the slash represents the mrdivide operation, not simple division. It matters when you are dealing with vectors and matrices.

请先登录,再进行评论。

采纳的回答

the cyclist
the cyclist 2022-1-23
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:
>> num2strexact(0.3)
ans =
0.299999999999999988897769753748434595763683319091796875

更多回答(1 个)

Voss
Voss 2022-1-23
It's not because of division, per se, but because of floating-point arithmetic.
No division here:
a = 3*0.3;
b = 0.9;
a == b
ans = logical
0
rel_err = (a-b)/a
rel_err = -1.2336e-16
abs_err = abs(a-b)
abs_err = 1.1102e-16

类别

Help CenterFile Exchange 中查找有关 Number Theory 的更多信息

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by