From: Justinas on
I have recently found some strange behaviour of MatLab and I would appreciate if somebody explained me why it happens and how to overcome this problem.

Please run the code:

x1 = [1/3 repmat(2/3,1,10)]';
x2 = [repmat(2/3,1,10) 1/3]';
mean(x1)==mean(x2)

% because

sum(x1)==sum(x2)

I get results false.

Why are the sums not the same although the difference between x1 and x2 is only the order of elements?
From: Matt Fig on
Don't feel bad, you are only the 1 millionth person to discover the wonders of floating point arithmetic. Have a read:

http://matlabwiki.mathworks.com/MATLAB_FAQ#Why_is_0.3-0.2-0.1_not_equal_to_zero_.28or_similar.29.3F
From: Walter Roberson on
Matt Fig wrote:
> Don't feel bad, you are only the 1 millionth person to discover the
> wonders of floating point arithmetic.

(1 millionth to within round-off error, that is.)
From: David Young on
If you look at the difference of the sums:

sum(x1)-sum(x2)

ans =

8.8818e-016

you can see that this is arithmetic rounding error. Values like 1/3 can't be expressed exactly as a binary expansion, so there are always approximations involved in computations involving such numbers. It's not surprising that the order in which the sums are computed makes a difference - I dare say someone could do a more detailed analysis of why these particular examples come out as they do.

The general message is this: it's not wise to use the == or ~= operators on double values, unless you know for sure that they have been computed in ways that avoid any truncation of a binary representation. The simplest thing is only to use the operators on the results of integer computations - otherwise use >, <=, >= and >, and instead of a==b use abs(a-b)<tol, where tol is an appropriate tolerance which may depend on your computation.
From: Parker on
On May 21, 10:55 pm, "Justinas " <justinas.bra...(a)gmail.com> wrote:
> I have recently found some strange behaviour of MatLab and I would appreciate if somebody explained me why it happens and how to overcome this problem.
>
> Please run the code:
>
> x1 = [1/3 repmat(2/3,1,10)]';
> x2 = [repmat(2/3,1,10) 1/3]';
> mean(x1)==mean(x2)
>
> % because
>
> sum(x1)==sum(x2)
>
> I get results false.
>
> Why are the sums not the same although the difference between x1 and x2 is only the order of elements?

always test equal like

>> x1 = [1/3 repmat(2/3,1,10)]';
>> x2 = [repmat(2/3,1,10) 1/3]';

>> if (mean(x1)-mean(x2))<eps
disp('Equal');
else
disp('Unequal');
end
>>>Equal
 |  Next  |  Last
Pages: 1 2
Prev: Curve matching question
Next: Mark S whorton