Are these expressions equivalent? (seeing greater errors in vectorized expression)
Show older comments
After converting a loop-based set of expressions to what I thought was a equivalent vectorized one I see a much more rapid accumulation of errors in a simple euler style numerical integration I am performing. This is confusing as the expressions appear to me to be equivalent. Does MATLAB use some reduced precision when computing vectorized expressions (float vs double maybe?). I can't think of any other reasons these two might not be equivalent.
Well, except for the fact that unlike other vectorized expressions, each element of B may be updated more than once here. I shouldn't think this should matter however since we are doing simple addition and the order that elements are updated does not matter.
Details of what the program is doing I don't think are relevant but follow the code snippet below
% loop-based expression
for j=1:size(L,1)
B(L(j,1),3:4)=B(L(j,1),3:4)+F1(j,:)./m.*dt;
B(L(j,2),3:4)=B(L(j,2),3:4)+F2(j,:)./m.*dt;
end
% Vectorized expression
B(L(:,1),3:4)=B(L(:,1),3:4)+F1./m.*dt;
B(L(:,2),3:4)=B(L(:,2),3:4)+F2./m.*dt;
F1 (note: F2=-F1) has two columns and the same number of rows as L.
Notes on what the script does:
This is from a simple toy script that performs a numerical integration of a mass-spring collection. These lines simply update the velocities of the blocks (B(:,3:4) are vx and vy). The spring links (L) columns 1 and 2 indicated which blocks are connected and tie back to that row in B. The force on each block at the end of each link (F1 and F2) is just above this in the script.
I can provide the entire script if needed.
6 Comments
Stephen23
on 14 Dec 2015
Are m and dt scalar?
Adam V Steele
on 14 Dec 2015
dpb
on 14 Dec 2015
"...since we are doing simple addition and the order that elements are updated does not matter."
That isn't necessarily so, no. Order in a summation over a larger number of terms can definitely have precision implications, especially if accumulating a smaller accretion to a larger.
Also, to the question re: internal precision of Matlab; the answer to it is "no"--calculations in Matlab are all on doubles unless you specifically cast to float so that won't be the difference.
Adam V Steele
on 14 Dec 2015
dpb
on 14 Dec 2015
I'd wager if you take the code snippets above out of the overall script and provide a set of static elements for the variables that you'll find for the single evaluation the results are identical. My guess is that it's owing to the fact it's in an integration routine and it's related to the path by which you get there; hence the comment regarding order possibly being significant (as well as the comment re: possible number of evaluations).
Adam V Steele
on 14 Dec 2015
Accepted Answer
More Answers (0)
Categories
Find more on Matrix Indexing 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!