Matlab-matrix-multiplication and transposition precision
The following 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 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 issue because when the format long
numbers are different in C and D.
- What am I doing wrong?
- Where is this happening?
- How can I avoid this?
source to share
You are not doing anything wrong - the computer has finite precision and your calculation shows it - just like 1e6 + 0.1 - 1e6
(try it in Matlab). One way to avoid this is to use some arbitrary precision library - but it will not "solve" it, it will just push the problem towards lower and lower numbers.
See these links for more information:
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 actual precision, it just sets up how the numbers are formatted to be displayed .
source to share