[Numpy-discussion] method to calculate the magnitude squared
nilsc.becker at gmail.com
Sun Oct 11 08:56:45 EDT 2015
I use complex numbers a lot and obviously need the modulus a lot. However,
I am not sure if we need a special function for _performance_ reasons.
At 10:01 AM 9/20/2015, you wrote:
It is, but since that involves taking sqrt, it is *much* slower. Even now,
In : r = np.arange(10000)*(1+1j)
In : %timeit np.abs(r)**2
1000 loops, best of 3: 213 Âµs per loop
In : %timeit r.real**2 + r.imag**2
10000 loops, best of 3: 47.5 Âµs per loop
This benchmark is not quite fair as the first example needs a python
function call and the second doesn't. If you benchmark a modulus function
against np.abs(x)**2 the performance gain is ca. 30% on my machine. This
means that for such a basic operation most of the time is spent in the
In my opinion if you want to have speed you write the modulus explicitly in
your expression (3-4x speedup on my machine). If you don't need speed you
can afford the function call (be it to abs2 or to abs).
By not providing abs2 in numpy, however, people do not loose out on a lot
There may be reasons to provide abs2 related to accuracy. If people (for
not knowing it better) use np.abs(x)**2 they lose significant digits I
think (may be wrong on that...). I did not look into it, though.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the NumPy-Discussion