Note that there are some explanatory texts on larger screens.

plurals
  1. POGenerating evenly distributed multiples/samples within a range
    primarykey
    data
    text
    <p><strong>Specific instance of Problem</strong><br> I have an int range from 1-100. I want to generate n total numbers within this range that are <strong>as evenly distributed as possible</strong> and include the first and last values.</p> <p><strong>Example</strong> </p> <pre><code>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] </code></pre> <p><strong>What I currently have</strong><br> 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?</p> <pre class="lang-python prettyprint-override"><code>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 </code></pre> <p>Note, I am ensuring that this function will always return at least the lower and upper limit values of the range. So, I force <code>n &gt;= 2</code></p> <p>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. </p> <p><strong>Solved: From the selected answer</strong></p> <p>I ended up using this slightly modified version of @vartec's answer, to be a generator, and also cap the <code>n</code> value for safety:</p> <pre><code>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)) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload