abs() is slow for complex, add abs2()
See original GitHub issueSee 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.
Issue Analytics
- State:
- Created 10 years ago
- Reactions:6
- Comments:19 (12 by maintainers)
Top Results From Across the Web
What is faster, abs(x) or x^2? - Performance - Julia Discourse
I need to compare many values to one. What would be faster: Option A: for i = 1 : N if abs(arr[i]) >...
Read more >Matlab speed: abs(x)^2 vs. x.*conj(x) - Google Groups
Hello, World! I'm interested in finding the energy contained in a given sequence, and have played about to find the most efficient way...
Read more >Why is numpy.absolute() so slow? - Stack Overflow
sum returns a scalar abs returns an array. So even if adding two numbers and taking the absolute had the same speed abs...
Read more >Absolute value and complex magnitude - MATLAB abs
abs (-0) returns 0 . Complex Magnitude. The complex magnitude (or modulus) is the length of a vector from the origin to ...
Read more >Performance Tips · The Julia Language
This is the single biggest advantage of @time vs. functions like tic() and ... try to rewrite code to use abs2() instead of...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
A proposal has been made for adding
abs2
to the array API specification. Were this proposal to be accepted, this is likely to affect the outcome of this issue and https://github.com/scipy/scipy/pull/15390.I’ve implemented a first version of
abs2()
in https://github.com/scipy/scipy/pull/15390.