Generating evenly distributed multiples/samples within a range

前端 未结 5 1713
说谎
说谎 2020-12-21 05:47

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

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-21 06:25

    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]
    >>>
    

提交回复
热议问题