colon operator rounding problem

조회 수: 1 (최근 30일)
Ambroise
Ambroise 2015년 7월 10일
편집: Stephen23 2015년 7월 10일
Hello everyone!
I encountered a problem in one of my code, using the semi colon operator like this:
a = 0:0.1:120;
will not give me exactly what I want, it does return 0, 0.1, 0.2 etc, but with a small imprecision (equal to eps actually)
the following code :
a = 0:0.1:120;
disp(a(20));
disp(a(20)-1.9)
isequal(a(20),1.9)
is returning:
1.9
2.22044604925031e-16
ans =
0
Any help ? I really need this isequal(a(20),1.9) to return 1...
thanks !
  댓글 수: 2
Ambroise
Ambroise 2015년 7월 10일
actually other values have a imprecision of n*eps, sometimes n=1, or n=8...

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

채택된 답변

bio lim
bio lim 2015년 7월 10일
Try it like this.
a=(0:1200)/10;
disp(a(20));
disp(a(20)-1.9);
isequal(a(20),1.9)
Your previous code was not returning 1 because of rounding errors when doing finite precision arithmetic.
  댓글 수: 3
Ambroise
Ambroise 2015년 7월 10일
and actually a=(0:1200)*0.1;
disp(a(20));
disp(a(20)-1.9);
isequal(a(20),1.9)
doesnt work but this works
a=(0:1200)/(1/0.1);
disp(a(20));
disp(a(20)-1.9);
isequal(a(20),1.9)
bio lim
bio lim 2015년 7월 10일
편집: bio lim 2015년 7월 10일
If you multiply it by decimals, such as 0.1, again you get rounding errors. That is why, I specifically wrote 10 in the first place. If you actually check your initial code, you can see that until a(4), it returns 0 but starts getting rounding error from that point.
1/0.1 returns 10 because, 1 is defined and when you divide you are going to get 10 without a rounding error.

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

추가 답변 (2개)

Thorsten
Thorsten 2015년 7월 10일
편집: Thorsten 2015년 7월 10일
Use
a = linspace(0, 120, 1201);
But in general don't use
a(20) == 1.9
but
abs(a(20) - 1.9) <= eps
If you don't want to do it this way, just define
a(20) = 1.9;

Steven Lord
Steven Lord 2015년 7월 10일
See question 1 in the Mathematics section of the FAQ for a more detailed explanation of this behavior.

카테고리

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

제품

Community Treasure Hunt

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

Start Hunting!

Translated by