Skip to content

abs() is slow for complex, add abs2() #3994

@Nodd

Description

@Nodd

See the following code (run on Ubuntu 64bits):

In [1]: import numpy as np

In [2]: b = np.random.rand(500, 500) + 1j * np.random.rand(500, 500)

In [3]: %timeit np.sqrt(b.real**2 + b.imag**2)
100 loops, best of 3: 4.15 ms per loop

In [4]: %timeit np.abs(b)
100 loops, best of 3: 6.06 ms per loop

abs() is slow compared to the manual formula. Is there any drawback in using np.sqrt(b.real**2 + b.imag**2) (like possible overflow ?)

Also, it could be useful to add an abs2() function which would return the value of abs()**2 but should be really faster for complex:

In [5]: %timeit b.real**2 + b.imag**2
1000 loops, best of 3: 1.4 ms per loop

It is commonly used to compute the energy of a signal or to sort complex numbers by norm value, for example.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions