KOB
KOB

Reputation: 1206

Matlab matrix-multiplication and transpose precision

The next script should print out a 7x7 all-ones matrix, because the equation is satisfied.

A = rand(5,7);
B = rand(5,7);

C = (A' * B)';
D =  B' * A;

C == D

Instead of this kind of answer:

ans =

 1     1     1     1     0     1     1
 1     1     1     1     0     1     0
 1     1     1     1     1     1     1
 1     1     1     1     0     0     0
 1     0     1     1     1     1     1
 0     0     1     1     1     1     1
 0     1     1     0     1     1     1

I think this is a floating-point precision problem, because with format long the numbers differ in C and D.

Upvotes: 3

Views: 278

Answers (1)

Itamar Katz
Itamar Katz

Reputation: 9645

You don't do anything wrong - the computer has finite precision, and your calculation reveals it - just like 1e6 + 0.1 - 1e6 (try it in Matlab). One way to avoid it is to use some library for arbitrary precision - but it won't 'solve' it, just push the problem towards smaller and smaller numbers.

See these links for some more info:

http://floating-point-gui.de/errors/comparison/

http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

By the way, format long has nothing to do with the actual precision, it just sets the way the numbers are formatted for displaying.

Upvotes: 4

Related Questions