Reputation: 1431
I do:
T = inv([1.0 0.956 0.621; 1.0 -0.272 -0.647; 1.0 -1.106 1.703]);
obtaining:
T =
0.2989 0.5870 0.1140
0.5959 -0.2744 -0.3216
0.2115 -0.5229 0.3114
if I do
T(1,1)==0.2989
i obtain
ans =
0
same for other elements. why this?
Upvotes: 1
Views: 54
Reputation: 78780
It's dangerous to test floating point numbers for exact equality. Per default, MATLAB uses 64 bits to store a floating point value, and some values such as 0.1
cannot even exactly be represented by an arbitrary number of bits. T(1,1)
is not exactly 0.2989
, which you can see when printing the value with a greater precision:
>> T = inv([1.0 0.956 0.621; 1.0 -0.272 -0.647; 1.0 -1.106 1.703])
T =
0.2989 0.5870 0.1140
0.5959 -0.2744 -0.3216
0.2115 -0.5229 0.3114
>> fprintf('%1.10f\n', T(1,1))
0.2989360213
This is why T(1,1) == 0.2989
returns false. It is safer to test whether two floating point values are almost equal, i.e. with regards to a tolerance value tol
:
>> tol = 1/1000;
>> abs(T(1,1) - 0.2989) < tol
ans =
1
Here's something you should probably read: click
Upvotes: 1
Reputation: 1133
MATLAB stores more digits than you usually see. The 0.2989 is actually 0.298936021293776 (and even that is not the end of the story). Try your code and add
format long
T(1,1)
but still,
T(1,1) == 0.298936021293776
ans =
0
So try
T(1,1) - 0.298936021293776
You just don't see all the digits. T(1,1)
is what it is supposed to be.
Upvotes: 2
Reputation: 314
Because they are not equal. Its just a display artefact. To see this:
fprintf('%.8f\n', T(1,1))
will give you
0.29893602
Upvotes: 2