 <p>You can avoid division by zero while maintaining performance by using advanced indexing:</p> <pre><code>x = np.arange(-500, 500) result = np.empty(x.shape, dtype=float) # set the dtype to whatever is appropriate nonzero = x != 0 result[nonzero] = 1/x[nonzero] result[~nonzero] = 0 </code></pre>