For Loop Not Executing

1 Ansicht (letzte 30 Tage)
Matthew Worker
Matthew Worker am 17 Sep. 2016
Kommentiert: Rena Berman am 8 Feb. 2017
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 Kommentare
Star Strider
Star Strider am 29 Jan. 2017
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 am 8 Feb. 2017
(Answers dev) Restored edit

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Mischa Kim
Mischa Kim am 17 Sep. 2016
Bearbeitet: Mischa Kim am 17 Sep. 2016
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 Kommentare
Star Strider
Star Strider am 17 Sep. 2016
As always, my pleasure.
N/A
N/A am 17 Sep. 2016
Of course! Thanks so much I should have realized this.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

David Goodmanson
David Goodmanson am 17 Sep. 2016
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.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by