What is the most efficient way of doing square root of sum of square of two numbers?

For the case of i != j it is not possible to do this with np.linalg.norm, thus I recommend the following:

(i*i + j*j)**0.5

If i and j are single floats, this is about 5 times faster than np.sqrt(i**2+j**2). If i and j are numpy arrays, this is about 20% faster (due to replacing the square with i*i and j*j. If you do not replace the squares, the performance is equal to np.sqrt(i**2+j**2).
Some timings using single floats:

i = 23.7
j = 7.5e7
%timeit np.sqrt(i**2 + j**2)
# 1.63 µs ± 15.6 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%timeit (i*i + j*j)**0.5
# 336 ns ± 7.38 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%timeit math.sqrt(i*i + j*j)
# 321 ns ± 8.21 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

math.sqrt is slightly faster than (i*i + j*j)**0.5, but this comes at the cost of losing flexibility: (i*i + j*j)**0.5 will work on single floats AND arrays, whereas math.sqrt will only work on scalars.

And some timings for medium-sized arrays:

i = np.random.rand(100000)
j = np.random.rand(100000)
%timeit np.sqrt(i**2 + j**2)
# 1.45 ms ± 314 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit (i*i + j*j)**0.5
# 1.21 ms ± 78.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Leave a Comment