Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating evenly distributed multiples/samples within a range

Tags:

python

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 as possible and include the first and last values.

Example

start = 1, end = 100, n = 5   
Output: [1, 25, 50, 75, 100]

start = 1, end = 100, n = 4   
Output: [1, 33, 66, 100]

start = 1, end = 100, n = 2   
Output: [1, 100]

What I currently have
I actually have a working approach but I keep feeling I am over thinking this and missing something more simple? Is this the most efficient approach or could this be improved?

def steps(start, end, n):
    n = min(end, max(n, 2) - 1)
    mult = end / float(n)
    yield start
    for scale in xrange(1, n+1):
        val = int(mult * scale)
        if val != start:
            yield val

Note, I am ensuring that this function will always return at least the lower and upper limit values of the range. So, I force n >= 2

Just for search reference, I am using this to sample image frames from a rendered sequence, where you would usually want the first, middle, last. But I wanted to be able to scale a bit better to handle really long image sequences and get better coverage.

Solved: From the selected answer

I ended up using this slightly modified version of @vartec's answer, to be a generator, and also cap the n value for safety:

def steps(start,end,n):
    n = min(end, max(n, 2))
    step = (end-start)/float(n-1)
    return (int(round(start+x*step)) for x in xrange(n))
like image 664
jdi Avatar asked Dec 12 '22 03:12

jdi


2 Answers

You need proper rounding:

def steps(start,end,n):
    if n<2:
        raise Exception("behaviour not defined for n<2")
    step = (end-start)/float(n-1)
    return [int(round(start+x*step)) for x in range(n)]
like image 105
vartec Avatar answered Dec 14 '22 16:12

vartec


Extra dependency and maybe overkill, but short, tested and should give correct results: numpy.linspace

>>> numpy.linspace(1, 100, 4).astype(int).tolist()
[1, 34, 67, 100]
like image 38
bmu Avatar answered Dec 14 '22 16:12

bmu