MATLAB Answers

Element wise multiplication .* rounding problem

3 ビュー (過去 30 日間)
Robin L.
Robin L. 2019 年 2 月 21 日
コメント済み: John D'Errico 2019 年 2 月 21 日
Hello,
My name is Robin and I am currently using Matlab to compute some calculations.
But I have an issue. Let's take :
M = 564;
P = sin(5);
disp((M.*10.*P) - (M.*(10.*P)));
The result should be 0. Instead I get :
ans = 9.0949e-13
I understand the gap is very small, but I think Matlab rounding algorithm should finally provide 0.
Can you help me ?

  0 件のコメント

サインインしてコメントする。

採用された回答

John D'Errico
John D'Errico 2019 年 2 月 21 日
編集済み: John D'Errico 2019 年 2 月 21 日
Nope. It does not. Welcome to the wild, whacky wonderful world of floating point numbers and arithmetic. A place where computations are only an approximation to mathematics, a model thereof. Where things like the associative law, the distributtive laws of arithmetic are only approximately true. A place where you need to learn to use tolerances on results, where you need to never trust the least significant bits of a result, at least not until you know, absolutely, because you fully understand the computations, what is happening. And even then, tolerances are still a good safety net, a good idea.
MATLAB does not automatically round everything that you do, expecting that a small number found really should be exactly zero. If it did, it would then introduce potential inaccuracies, even beyond those created by the use of floating point numbers themselves.
And if it did, do you think a chemist would be happy to see the reciprocal of Avogadro's number always be shown as exactly zero?

  0 件のコメント

サインインしてコメントする。

その他の回答 (2 件)

madhan ravi
madhan ravi 2019 年 2 月 21 日
Second John D’Erricos answer as a workaround if you have symbolic math toolbox:
P=sym(sin(5)); % just alter your line to this

  0 件のコメント

サインインしてコメントする。


Robin L.
Robin L. 2019 年 2 月 21 日
Thank you John D'Errico and madhan ravi !
So I consider that no formula is better than the other, between :
(M.*10).*P
and
M.*(10.*P)
Because each result is an approximation, and the gap between both values is finally unsignificant for me.

  1 件のコメント

John D'Errico
John D'Errico 2019 年 2 月 21 日
Please don't add an answer just ot make a comment.
But, yes, the associative law has problems in floating point arithmetic. Both expressions are valid, yet they can yield different results in the least significant bits.

サインインしてコメントする。

Community Treasure Hunt

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

Start Hunting!

Translated by