Matrix multiplication accuracy problem
Show older comments
I made a function that calculates autocorrelation using partial matrices. When I tried to verify it by comparing with autocorrelation using whole matrices, I thought I had made a mistake, but then I found out Matlab gives different results depending on how the matrix is separated into parts. However, there should be no difference between the calculations!
Now, do not give me mere floating point arithmetic as the explanation: It does NOT explain this difference.
Here is a very simple test that shows the problem:
a1=randn(100,1); a2=randn(100,1);
A=[a1 a2];
R0=A'*A;
R1=[a1 a2]'*[a1 a2];
R2=[a1'*a1 a1'*a2; a2'*a1 a2'*a2];
[R0-R1 R2-R1]
ans =
1.0e-13 *
0.1421 -0.0089 0.2842 -0.0089
-0.0089 -0.2842 -0.0089 0
If you know anything about matrix algebra, you should know that R0 is internally calculated EXACTLY in the same way as R1 and R2 above. So, floating point arithmetic as such does not explain the difference.
So, obviously Matlab must be rounding the intermediate results differently in these cases, but I cannot understand WHY they are rounded differently? There is no sensible reason in these cases to do it differently. Mathworks, why you are doing this? It just makes all verification more difficult when the results are not what they are supposed to be.
Accepted Answer
More Answers (1)
John D'Errico
on 21 Jan 2021
2 votes
The Mathworks is NOT rounding numbers just to make your life difficult. They are not rounding numbers at all, at least not beyond that which happens in normal floating point arithmetic. And apparently, you are telling us that we cannot tell you the answer, since you already "know" what it is.
What you do not seem to appreciate is that MATLAB uses the blas to do linear algebra. This makes your computations more efficient. At the same time, the blas can change the sequence of the computations involved. And as soon as you play with the sequence of the adds in a computation, you incur the possibility that you will see a problem.
So I'm sorry, but what you "know" about matrix agebra does not always apply. Mathematical proofs do not apply down in the least significant bits of floating point numbers.
3 Comments
Petri M
on 21 Jan 2021
Petri M
on 21 Jan 2021
John D'Errico
on 22 Jan 2021
Edited: John D'Errico
on 22 Jan 2021
So, I was not completely wrong. What I was wrong about was not capitalizing the letters in blas? Sorry for laughing. Actually, no. I'm still laughing. This is not a case of some ingenuous rounding.
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!