Hi all!
Consider the following example:
h=(2/1000);
for i=8*h+h:h:9*h
i
end
i =
0.0180
And similarly,
>> for i=11*h+h:h:12*h
i
end
i =
0.0240
But when I do this:
>> for i=9*h+h:h:10*h
i
end
it doesn't enter the for loop! What is going on? Thanks for the help!

댓글 수: 2

Star Strider
Star Strider 2017년 1월 29일
You can go as far as you did, but Rena Berman will reconstitute it in a few days.
Does Sisyphus begin to sound relevant?
Rena Berman
Rena Berman 2017년 2월 8일
(Answers dev) Restored edit

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

 채택된 답변

Mischa Kim
Mischa Kim 2016년 9월 17일
편집: Mischa Kim 2016년 9월 17일

1 개 추천

Gopal, this is because
9*h+h - 10*h
ans =
3.469446951953614e-18
and
11*h+h - 12*h
ans =
0
Just because the terms above are all symbolically equal to zero, does not necessarily mean they are also numerically equal to zero. The first expression is not which is why the loop does not get executed.
Star Strider provides more detail below.

댓글 수: 4

Almost.
In the top two, the end equals the beginning, so the loops in them execute once. The loop is satisfied after the first iteration.
In the third one, the difference between the end and the beginning is negative, so the loop is satisfied at the first iteration and never executes:
h=(2/1000);
d = [ 9*h - (8*h+h); 12*h - (11*h+h); 10*h - (9*h+h)]
d =
0
0
-3.4694e-18
Because of the negative direction:
for i=9*h+h:-h:10*h
i
end
i =
0.02
executes once with a step of ‘-h’.
Mischa Kim
Mischa Kim 2016년 9월 17일
Absolutely. Thanks.
Star Strider
Star Strider 2016년 9월 17일
As always, my pleasure.
N/A
N/A 2016년 9월 17일
Of course! Thanks so much I should have realized this.

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

추가 답변 (1개)

David Goodmanson
David Goodmanson 2016년 9월 17일

0 개 추천

For the floating point number h you are basically asking if n*h + h == (n+1)*h for various values of n. Well, sometimes the two sides are equal (to machine precision), sometimes not. For n=9 the left hand side is bigger than the right hand side by 3e-18, so the for loop doesn't do anything.
It's never a good idea to do exact equality tests with floating point numbers.

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

질문:

2016년 9월 17일

댓글:

2017년 2월 8일

Community Treasure Hunt

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

Start Hunting!

Translated by