# HP Forums

Full Version: FOR LOOP "STEP" ?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
This is peculiar to say the least:

Quote:EXPORT Test()
BEGIN
LOCAL angl;
print();

// FOR LOOP STEPS: pi/6"
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;

// WHILE LOOP Increment pi/6
angl:=0;
WHILE angl <= pi DO
IF angl == pi/3 then
PRINT("WHILE LOOP is TRUE"); // Loop works!
END;
angl:=angl+pi/6; // Step increment pi/6
END;

END;

I was trying to step around a circle, and could not get the STEP increment in a FOR loop to work for me. It worked as expected using other approaches. What's going on with the FOR's <STEP> increment?

-Dale-
(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
Hello

Quote:This is peculiar to say the least:

FOR A FROM 0 to pi STEP pi/6 DO
IF A == pi/3 then
print("IT NEVER GETS THERE!!!!!!");
END;
END;

Yes, you are correct! interestingly, if you print the successive values of A, you will see that the 2nd value is not what you would expect it to be.
The reason for it is that the 'step' is done in a full 15 digit precision add instead of a rounded 12 digit. This is what causes the issue.