Does order of multiplication in a for loop matter?
2 views (last 30 days)
Show older comments
I am currently trying to rewrite my code in a way to get rid of the for loops I have, but as I was doing that, I stumbled on something that is making me worry that my code is not giving me the correct results. I rewrote the same terms in the for loop, but in a different order and it gave different things, I wanted to know why.
I have:
l1 = zeros(Nx_max,Ny_max);
l2 = zeros(Nx_max,Ny_max);
nx = Nx_max-1;
ny = Ny_max-1;
for x = 2:nx
for y = 2:ny
l1(x,y) = (2*dxx(x,y) +2*dyy(x,y))*(1/(h^2))*p(x,y,t1);
l2(x,y) = (2*dxx(x,y) + 2*dyy(x,y))*p(x,y,t1) * (1/(h^2));
end
end
diff = sum(sum(l1-l2))
I would expect if these are the same that diff = 0 (and they should be the same since all I did was change the order of multiplying one term in the for loop (at each iteration in the loop all terms are just numbers, so there should be no difference in order).
But I do not get zero. And I'm not sure why.
Note:dxx,dyy, and p are all arrays of the same size as l1 and l2. h is just a number
1 Comment
Matthew Eicholtz
on 13 Aug 2014
p does not appear to be the same size as l1 (3D vs 2D). Also, what is t1?
Answers (2)
Matthew Eicholtz
on 13 Aug 2014
Also, just a suggestion, avoid using built-in MATLAB functions as variable names (e.g. diff).
dpb
on 13 Aug 2014
Edited: dpb
on 13 Aug 2014
...I would expect ... should be the same since all I did was change the order of multiplying one term in the for loop...
That's naive expectation -- while commutativity and associativity are true in pure mathematics, floating point arithmetic is only an approximation (and a fairly crude one at that, albeit still quite useful). Precise equality in the case of rearranging terms isn't always going to happen (for other than integer arguments that don't exhibit under- or over- flow, anyway) owing to the difference in precisely how roundoff/truncation to the limited precision of the hardware occurs between the two sequences.
For the details in all their gory fullness, see Goldberg's paper
I would expect if you look at something like
max(l1(:)-l2(:))
you'd find the actual difference isn't huge but at the limits of what double precision accuracy is.
6 Comments
Roger Stafford
on 14 Aug 2014
"the rules of associativity/commutivity aren't exact in floating point as they are in mathematics." I still object to your inclusion of commutativity in this expression of inexactness. Commutativity is understood as applying only to binary operations, A op B = B op A, and as such the matlab operations of addition and multiplication are precisely commutative. No ifs, ands, or buts.
dpb
on 14 Aug 2014
OK, so it's a semantics problem -- what do you want to call the order sequencing that I lumped into associativity?
See Also
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!