Post Reply 
FOR LOOP "STEP" ?
01-31-2015, 06:50 PM
Post: #2
RE: FOR LOOP "STEP" ?
(01-31-2015 04:27 PM)DrD Wrote:  This is peculiar to say the least:

This could be a simple example for one of the many numerical pitfalls when working with reals. ;-)

(01-31-2015 04:27 PM)DrD Wrote:  
Code:
FOR angl FROM 0 to pi STEP pi/6 DO
  IF angl == pi/3 then
    PRINT(" FOR LOOP is TRUE");  //  Loop fails test ... bad dog!
  END;
END;

It's generally not a good idea to compare reals with "=". Just a slight roundoff error in the last digit, and the test will fail. This may (!) be the crucial point here.
You may try a different less error-prone test instead, something like IF abs(angl – pi/3) < 1E–9 THEN ...

Or, even better, use an integer counter variable:

Code:
FOR k FROM 0 to 6 DO
    angl:=k*pi/6;
    IF k==2 then
    PRINT("BINGO"); 
  END;
END;

Dieter
Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
FOR LOOP "STEP" ? - DrD - 01-31-2015, 04:27 PM
RE: FOR LOOP "STEP" ? - Dieter - 01-31-2015 06:50 PM



User(s) browsing this thread: 1 Guest(s)