For Loop Not Executing
显示 更早的评论
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
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
2017-2-8
(Answers dev) Restored edit
采纳的回答
更多回答(1 个)
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 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!