Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The following code gives a nice increase in performance that depends upon how dense the numbers are. Using a set of 1000 random numbers, sampled uniformly between 0 and 100, it runs about 30 times faster than your implementation.</p> <pre><code>pos_1_start = 0 for i in range(np.size(vector1)): for j in range(pos1_start, np.size(vector2)): if np.abs(vector1[i] - vector2[j]) &lt; .02: results1 += [(vector1[i], vector2[j], i, j)] else: if vector2[j] &lt; vector1[i]: pos1_start += 1 else: break </code></pre> <p>The timing:</p> <pre><code>time new method: 0.112464904785 time old method: 3.59720897675 </code></pre> <p>Which is produced by the following script:</p> <pre><code>import random import numpy as np import time # initialize the vectors to be compared vector1 = [random.uniform(0, 40) for i in range(1000)] vector2 = [random.uniform(0, 40) for i in range(1000)] vector1.sort() vector2.sort() # the arrays that will contain the results for the first method results1 = [] # the arrays that will contain the results for the second method results2 = [] pos1_start = 0 t_start = time.time() for i in range(np.size(vector1)): for j in range(pos1_start, np.size(vector2)): if np.abs(vector1[i] - vector2[j]) &lt; .02: results1 += [(vector1[i], vector2[j], i, j)] else: if vector2[j] &lt; vector1[i]: pos1_start += 1 else: break t1 = time.time() - t_start print "time new method:", t1 t = time.time() for lv1 in range(np.size(vector1)): for lv2 in range(np.size(vector2)): if np.abs(vector1[lv1]-vector2[lv2])&lt;.02: results2 += [(vector1[lv1], vector2[lv2], lv1, lv2)] t2 = time.time() - t_start print "time old method:", t2 # sort the results results1.sort() results2.sort() print np.allclose(results1, results2) </code></pre>
 

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