필터 지우기
필터 지우기

Issues with The Colon (:) Operator

조회 수: 14 (최근 30일)
Royi Avital
Royi Avital 2015년 5월 20일
댓글: Stephen23 2020년 4월 22일
Hello,
I have an issue with the colon operator which operates differently than expected.
Let's define the following vectors:
vA = 30:0.0025:60;
vB = 30:0.0025:70;
Now, since their starting point and step size are identical I'd expect their values to match in the overlap zones.
Yet, try this:
a = vA(642);
b = vB(642);
isequal(a, b)
a - b
As one could see, the result is different (46.0249999999 vs. 46.0250000006). This is very different from the documentation of the colon operator .
I was expecting its values no to be dependent on the end value (Only the number of steps depend on the end value).
Is it a bug or am I missing something?
Thank You.

채택된 답변

Guillaume
Guillaume 2015년 5월 20일
The behaviour of colon used to be fully documented in older versions and in a technical solution on Mathworks website. Unfortunately, that documentation has been removed in newer versions and the link on Mathworks is dead.
This answer gives you the details.
Basically, with non-integer steps, colon works from both ends to avoid accumulating errors. I can't fathom why Mathworks thinks that information is no longer relevant.
  댓글 수: 3
Aravind C G
Aravind C G 2020년 4월 22일
편집: Aravind C G 2020년 4월 22일
Wow, thank you for this answer that clarifies things. I stumbled upon a similar issue while using the colon operator to pass a range of decimal values into a function. Sometimes the size of the functions output would be [1 19] and at others [1 20]
Now I see where the problem is coming from.
Edit: Ah, now I see it is included in the latest documentation as:
"However, if i is not an integer, then floating point arithmetic plays a role in determining whether colon includes the endpoint k in the vector, since k might not be exactly equal to j+m*i"
Stephen23
Stephen23 2020년 4월 22일
The provided links are now dead, but these appear to provide the relevant information:
The original technical explanation (since removed from the TMW website) is archived here:

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by