Reputation: 1
For my application I need to loop (for loop) over ranges of float values and sometimes with non-integer start, stop and step values. While I can make python range and numpy.arange() (which only operate on integers) work with multiplication or division, it becomes cumbersome to work with given the number of possible steps sizes, the precision of them, etc. So I prefer to use numpy.linspace() since it can use floats however, linspace needs a number of steps, rather than a step size, which is also slightly cumbersome for my application. Steps size is much easier to work with.
With the above in mind, I created a way of creating an array of values based upon an arbitrary start, stop and step size of floating values.
The one real issue is that the step size is sometimes not exactly what you wanted because of rounding errors (see Output 2 below) but this is not a major issue in my application. I can live with it but it would of course be desirable to be spot on.
Now that a have an array of floats, I can just iterate over that.
It's not perfect but I wonder if anyone has a better way or improvements to make to this.
import numpy as np
Start = -5.0
Stop = -2.0
stepSize = 0.25 # the step size will be approximate in the end
numSteps = abs(int(np.floor_divide(Stop-Start,stepSize))) # determine necessary number of steps
partial = np.linspace(Start,Stop,numSteps,endpoint=False,dtype=float) # create array of all but last value
aStop = [Stop] # create array of last value
full = np.hstack((partial,aStop)) # stack (concatenate) the two arrays horizontally
print("\nStart= {0:2.3f} Stop= {1:2.3f} stepSize= {2:2.3f}\n". format(Start, Stop, stepSize))
for k in full:
print(k)
# note: if stop and step do not cleanly divide into each other, you won't get the full last step. This is OK for my application.
endpoint = false (within linspace) is important because otherwise it will attempt to create steps with the stop point included, which is not what I need. So then I just add the Stop point afterward.
Output 1:
Start= -5.000 Stop= -2.000 stepSize= 0.250
-5.0 -4.75 -4.5 -4.25 -4.0 -3.75 -3.5 -3.25 -3.0 -2.75 -2.5 -2.25 -2.0
Output 2:
Start= -5.000 Stop= -1.900 stepSize= 0.300
-5.0 -4.69 -4.38 -4.07 -3.76 -3.45 -3.14 -2.83 -2.52 -2.21 -1.9
Upvotes: -2
Views: 33