Matrix Equality Check Failed Using == and isequal

조회 수: 1 (최근 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 CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by