Discussion:
[Numpy-discussion] method to calculate the magnitude squared
Phillip Feldman
2015-09-19 04:16:42 UTC
Permalink
In communications and signal processing, it is frequently necessary to
calculate the power of a signal. This can be done with a function like the
following:

def magsq(z):
"""
Return the magnitude squared of the real- or complex-valued input.
"""
return z.real**2 + z.imag**2

A high percentage of the scripts that I write contain or import a function
like this. It would be great if there were a built-in method in NumPy,
preferably with a name like `magsq`, `mag2`, or `msq`.

Phillip
R Schumacher
2015-09-19 04:41:35 UTC
Permalink
Post by Phillip Feldman
In communications and signal processing, it is
frequently necessary to calculate the power of a
  """
  Return the magnitude squared of the real- or complex-valued input.
  """
  return z.real**2 + z.imag**2
Is that not the same as
np.abs(z)**2 ?

- Ray
Marten van Kerkwijk
2015-09-20 17:01:29 UTC
Permalink
Post by R Schumacher
Is that not the same as
np.abs(z)**2 ?
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
```

-- Marten
R Schumacher
2015-09-20 19:39:44 UTC
Permalink
Post by R Schumacher
Is that not the same as
  np.abs(z)**2 ?
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
-- Marten
Ahh yes, a full extra step, "back"
Assuming these are spectra, how does timeit do
with scipy.signal.periodogram (using appropriate n and scaling)?

- Ray
Antoine Pitrou
2015-09-20 20:41:32 UTC
Permalink
On Fri, 18 Sep 2015 21:16:42 -0700
Post by Phillip Feldman
In communications and signal processing, it is frequently necessary to
calculate the power of a signal. This can be done with a function like the
"""
Return the magnitude squared of the real- or complex-valued input.
"""
return z.real**2 + z.imag**2
A high percentage of the scripts that I write contain or import a function
like this. It would be great if there were a built-in method in NumPy,
preferably with a name like `magsq`, `mag2`, or `msq`.
Are you asking for speed or convenience reasons?

Regards

Antoine.

Loading...