Skip to main content

I tried those code:

FOR i = -0.500, 0.500, 0.1
      PRINT $STR(i)," ",
NEXT
PRINT
! This one starts from -0.5 and ends at 0.5


FOR i = -0.500, 0.500, 0.05
      PRINT $STR(i)," ",
NEXT
PRINT

! This one starts from -0.5 and ends at 0.5

FOR i = -0.500, 0.500, 0.01
      PRINT $STR(i)," ",
NEXT
PRINT

! This one starts from -0.5 and ends at 0.49, WHY?

 

Thanks!

Xing

 

Hi Xing,

This is due to precision errors with floating point numbers and there is really no way to avoid this in programming.  Ideally, when using a FOR loop with the ZPL, you should only use integers for the startstop, and increment.  If you need a decimal number inside the loop, then you should calculate that number inside the actual loop and not rely on a fraction coming from the loop counter.  For example, if you want to step through the normalized pupil coordinates with 11 steps, you FOR loop should look like:
 

numSteps = 11  # this should be odd
minus1 = numSteps - 1
FOR i = 0, minus1, 1
py = (i - minus1) / minus1
PRINT py, ", ",
NEXT

This will print -1.0, -0.8, -0.6, -0.4, -0.2, 0.0, 0.2, 0.4, 0.6, 0.8, 1.0.  There will be no ambiguity when to start & stop the loop and you get your decimal values you want calculated inside the FOR loop.


Hi Michael,

 

Thanks for the information!

 

Xing


Reply