Skip to main content
Solved

For loop start and end


Xing
  • Single Emitter
  • 1 reply

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

 

Best answer by MichaelH

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.

View original
Did this topic help you find an answer to your question?

2 replies

MichaelH
Ansys Staff
Forum|alt.badge.img+2
  • Ansys Staff
  • 381 replies
  • Answer
  • July 15, 2025

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.


Xing
  • Author
  • Single Emitter
  • 1 reply
  • July 15, 2025

Hi Michael,

 

Thanks for the information!

 

Xing


Reply


Cookie policy

We use cookies to enhance and personalize your experience. If you accept you agree to our full cookie policy. Learn more about our cookies.

 
Cookie settings