Fast lookup from floating point index into array
<p>Suppose I have <code>n</code> intervals of length <code>len</code> on an axis. Each of them is assigned a value in an <code>ndarray</code>. Now I'd like to look-up some values at positions <code>query_pos</code> given as floating point numbers. Currently, I plan to do it the following way:</p>

<pre><code>n = 100
len = 0.39483
data = ... # creates ndarray with data of length n = 100
query_pos = ... # creates an ndarray with positions to query
values_at_query_pos = data[(query_pos / len).astype(int)] # questionable line
</code></pre>

<p><strong>Is that a good way to do it or are there more efficient ways to convert a floating point query position into an integer index and then read from an array?</strong> I particularly wonder, wether <code>astype(int)</code> is a cheap or an expensive operation, compared for example to the division or the memory read.</p>

<p>Some more remarks:</p>

<ul>
<li><p>Finally, it will be used in 2 and 3 dimensions. Currently, I plan to
catch positions that would lead to illegal indices <em>before</em> they go
into the lookup stage.</p></li>
<li><p>The <code>data</code> array will have a high-enough resolution so that I don't
need any filtering or interpolation. That will be done in previous
stages.</p></li>
</ul>

<p>You can output the result of the division straight to an <code>int</code> array:</p>

<pre><code>idx = np.empty_like(query_pos, int)
np.divide(query_pos, len, out=idx, casting='unsafe')
</code></pre>

<p>This will be noticeably faster only for large arrays. But this code is harder to read, so only optimize if it's a bottleneck!</p>

python numpy optimization floating-point indices