When I write a program about consumption (C) with 10^5 trajectories, I want to calculate the expectation of them with the command mean(C(:,j)). However, at j=1, all the C are equal to 0.86, but the mean(C(:,1))=0.859999999999891. Would anyone tell me why it happens and how to correct it please? Thank you.

 채택된 답변

Tom Lane
Tom Lane 2012년 5월 21일

0 개 추천

As Oleg and Titus imply, one idea is to change the test so that it allows for things that differ by a small amount to be treated as roughly equal. Another thing that sometimes works is to refine your answer by another application of mean. This works in some cases but doesn't change the fundamental fact that two theoretically identical things may be slightly different when represented by double precision on a computer. Anyway, here's what I had in mind:
>> x = repmat(0.86,1e5,1);
>> fprintf('%25.18g\n',x(1))
0.85999999999999999
>> m = mean(x); fprintf('%25.18g\n',m)
0.86000000000030574
>> m = m + mean(x-m); fprintf('%25.18g\n',m)
0.85999999999999999

추가 답변 (1개)

Titus Edelhofer
Titus Edelhofer 2012년 5월 21일

0 개 추천

Hi,
0.86 is not exactly representable in computers double precision representation:
fprintf('%.20f\n', 0.86)
0.85999999999999999000
Titus

댓글 수: 3

Oleg Komarov
Oleg Komarov 2012년 5월 21일
http://matlab.wikia.com/wiki/FAQ#Why_is_0.3_-_0.2_-_0.1_.28or_similar.29_not_equal_to_zero.3F
Tommy
Tommy 2012년 5월 21일
then would you please tell me how to get the right answer please? since I need the correct one to finish the loop of
if C(i,j)>=mean(C(:,j))
THX a lot!
Walter Roberson
Walter Roberson 2012년 5월 21일
Recode your test to
if C(i,j) * size(C,1) >= sum(C(:,j))

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

태그

질문:

2012년 5월 21일

Community Treasure Hunt

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

Start Hunting!

Translated by