Matrix Equality Check Failed Using == and isequal

2 ビュー (過去 30 日間)
Yiping Wang
Yiping Wang 2019 年 8 月 16 日
編集済み: John D'Errico 2019 年 8 月 16 日
Hello guys,
I am confused about how MATLAB handles matrix equailty check. Consider the following example,
a = [262 -200; -200 200];
a_inv = inv(a);
% since it is a 2 by 2 matrix, we can perform inv operation like this
b = (1/(262 * 200 - 200*200)) * [200 200; 200 262];
a_inv == b
% 2×2 logical array
%
% 0 0
% 0 0
isequal(a_inv, b)
% ans =
%
% logical
%
% 0
But when I print these matrix, it gives me exact same result
format long
a_inv
a_inv =
0.016129032258065 0.016129032258065
0.016129032258065 0.021129032258065
b
b =
0.016129032258065 0.016129032258065
0.016129032258065 0.021129032258065
Not sure which step did I do wrong? ang suggestion to compare matrix properly?

採用された回答

John D'Errico
John D'Errico 2019 年 8 月 16 日
編集済み: John D'Errico 2019 年 8 月 16 日
NEVER test for exact equality of floating point matrices. It won't happen, at least not unless you are very, very lucky.
a_inv - b
ans =
3.46944695195361e-18 3.46944695195361e-18
3.46944695195361e-18 3.46944695195361e-18
Welcome to the wacky, winderful world of floating point arithmetic. Computation of numbers, even if they are mathematically identical does not mean that they will be identical in floating point arithmetic. The classical example is just
0.3 - 0.2 - 0.1
ans =
-2.77555756156289e-17
Use a tolerance to test for CLOSENESS instead.
  2 件のコメント
Yiping Wang
Yiping Wang 2019 年 8 月 16 日
I see. Thanks for the tip!
John D'Errico
John D'Errico 2019 年 8 月 16 日
編集済み: John D'Errico 2019 年 8 月 16 日
It is actually fairly easy to look at those numbers, and think they look the same. But MATLAB only showed 15 significant digits there, and the difference between those numbers was in the next decimal place, the one essentially not shown.
As stored in MATLAB, down to the last binary bit, here are the mantissas for those two numbers:
b(1,1): '10000100001000010000100001000010000100001000010000100'
a_inv(1,1): '10000100001000010000100001000010000100001000010000101'
So the two numbers were identical all the way down to that least significant bit, where they differed. But that was sufficient to make them unequal.
As a test for example, I might have done this instead:
norm(a_inv - b)
ans =
6.93889390390723e-18
If that norm was sufficiently small, then I might decide the matrices were close enough for my purposes.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by