Specific instance of Problem
I have an int range from 1-100. I want to generate n total numbers within this range that are as evenly distributed
The problem with using range
is that the step must be an integer and so you get rounding issues, such as steps(1,100,4) == [1, 33, 66, 100]
. If you want integer outputs but want as even a step as possible, use a float as your step.
>>> def steps(start,end,n):
... step = (end-start)/float(n-1)
... return [int(round(start+i*step)) for i in range(n)]
>>> steps(1,100,5)
>>> [1, 26, 51, 75, 100]
>>> steps(1,100,4)
>>> [1, 34, 67, 100]
>>> steps(1,100,2)
>>> [1, 100]
>>>