Matrix Equality Check Failed Using == and isequal

2 views (last 30 days)
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?

Accepted Answer

John D'Errico
John D'Errico on 16 Aug 2019
Edited: John D'Errico on 16 Aug 2019
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 Comments
John D'Errico
John D'Errico on 16 Aug 2019
Edited: John D'Errico on 16 Aug 2019
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.

Sign in to comment.

More Answers (0)

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!