sum() function in different Matlab version give different result

조회 수: 4 (최근 30일)
Hope
Hope 2012년 9월 20일
I use sum() function in my code. I find it give different result in different Matlab version, such as Matlab 7.0 and Matlab 7.9. I load data from .mat file and compute sum of a 300dim vector. It gives the same result when computing sum of the first 100dim, but gives different results for the total 300dim. I wonder why? And how to deal with it?

채택된 답변

Matt Fig
Matt Fig 2012년 9월 20일
편집: Matt Fig 2012년 9월 20일
How different are the results, percent-wise?
It is possible that the underlying algorithm has changed, and of course the order of summation affects things in floating point arithmetic. For example:
>> N = 3e6;
>> a = rand(1,N);
>> S1 = sum(a);
>> S2 = sum(a(randperm(N)));
>> (S2-S1)/S1 % Not zero.
ans =
-1.3355e-014
  댓글 수: 5
Jan
Jan 2012년 9월 22일
편집: Jan 2012년 9월 23일
As far as I know, SUM uses multiple threads only if 89000 ore more elements are processed. Then in R2009a the results from the different threads are added in the order the corresponding threads are finished. Therefore the results can randomly switch between a set of values. But I've do not think that happens for 300 elements in any Matlab version.
The order of the elements matters for small vectors also:
s1 = 1 + 1e17 - 1e17 - 1; % replies -1
s2 = -1 - 1e17 + 1e17 + 1; % replies +1
[EDITED after James comment] Doh! Of course I meant 1e17 instead of 1e7. But another problem remains: There is no indication that Matlab evaulates the SUM in backward direction ever. But the above argument matters, if e.g. the sum is distributed to 4 threads. Then the order of adding the partial sums matter. If 128 Bit registers of the SSE-unit are used, this is equivalent to sum(1:2:end) + sum(2:2:end). Unfortunately the underlying method is not documented.
James Tursa
James Tursa 2012년 9월 22일
@Jan: I think you are missing something in your post. In double precision, both s1 and s2 are 0. Were you meaning to do a single precision example, or ...?

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by