1

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?

dertkw
  • 7,798
  • 5
  • 37
  • 45
volperossa
  • 1,339
  • 20
  • 33

3 Answers3

2

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.

Yair Daon
  • 1,043
  • 2
  • 15
  • 27
  • how can I view all the digits?? – volperossa Jun 13 '14 at 17:51
  • I don't really know. But - why would you want to see all digits? If you want to check for equality, check if the two numbers are within some tolerance from each other. – Yair Daon Jun 13 '14 at 17:57
  • 1
    I need to replicate the same behavior without call inv function (so i need just the numbers to use in a product... I resolve with fprintf('%.55f\n', T(1,1)) XD – volperossa Jun 13 '14 at 18:14
2

Because they are not equal. Its just a display artefact. To see this:

fprintf('%.8f\n', T(1,1))

will give you

0.29893602
Jasper Uijlings
  • 314
  • 2
  • 5
1

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

Community
  • 1
  • 1
timgeb
  • 76,762
  • 20
  • 123
  • 145