[Numpy-discussion] method to calculate the magnitude squared
Nils Becker
nilsc.becker at gmail.com
Sun Oct 11 08:56:45 EDT 2015
Hey,
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 [32]: r = np.arange(10000)*(1+1j)
In [33]: %timeit np.abs(r)**2
1000 loops, best of 3: 213 µs per loop
In [34]: %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
function call.
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
of performance...
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.
Cheers
Nils
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20151011/48799dbc/attachment.html>
More information about the NumPy-Discussion
mailing list