Python definition function and for range() loop

96 views Asked by At

I have a defined function:

def micronToStep(v):
    #approximately 62nm/step
    return round((v * 1000)/62)

And the command for range() loop:

xyStep = 5
xRange = 400

for x in range(-micronToStep(xRange/2), micronToStep(xRange/2) - micronToStep(xyStep), micronToStep(xyStep))

For xyStep = 5, xRange = 400 the command: len(range(-micronToStep(xRange/2), micronToStep(xRange/2) - micronToStep(xyStep), micronToStep(xyStep))) returns 79, which not exceed the limit xRange/xyStep = 80.

But for xyStep = 1, xRange = 400 the len(range()) function returns incorrect value 403 instead of value less or equal to xRange/xyStep = 400.

I think the problem lies in micronToStep() function.

How to correct this, that for range() loop would not exceed the limit of xRange/xyStep by number of iterations?

2

There are 2 answers

0
Malum Phobos On

I figured out that using ceil() instead of round() in micronToStep() function works pretty good but I think it's not an optimal solution.

5
itprorh66 On

I believe you can solve your problem as follows:

xyStep = 1
xrange = 400
[micronStep(x) for x in range(xrange//2, (xrange//2 - xyStep), xyStep]

This yields a list of length 399, and additionally simplifies the computation, since micronToStep is only called once for each step.