Does order of multiplication in a for loop matter?
조회 수: 3 (최근 30일)
이전 댓글 표시
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
Matthew Eicholtz
2014년 8월 13일
p does not appear to be the same size as l1 (3D vs 2D). Also, what is t1?
답변 (2개)
Matthew Eicholtz
2014년 8월 13일
Also, just a suggestion, avoid using built-in MATLAB functions as variable names (e.g. diff).
dpb
2014년 8월 13일
편집: dpb
2014년 8월 13일
...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
Roger Stafford
2014년 8월 14일
"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
2014년 8월 14일
OK, so it's a semantics problem -- what do you want to call the order sequencing that I lumped into associativity?
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!