The square root of all values ​​in the numpy array preserving the sign

I would like to take the square root of each value into a numpy array, preserving the sign of the value (and not returning complex numbers if the value is negative) - the signed square root.

The code below demonstrates the desired w / lists functionality, but does not take advantage of the numpy-optimized superpower-driven array.

def signed_sqrt(list): new_list = [] for v in arr: sign = 1 if v < 0: sign = -1 sqrt = cmath.sqrt(abs(v)) new_v = sqrt * sign new_list.append(new_v) list = [1., 81., -7., 4., -16.] list = signed_sqrt(list) # [1., 9., -2.6457, 2. -4.] 

In some context, I compute Healing Healing to compare [thousands] of images.

Any smooth way to do this with numpy? Thanks.

+5
source share
1 answer

You can try using the numpy.sign function to capture the character and just take the square root of the absolute value.

 import numpy as np x = np.array([-1, 1, 100, 16, -100, -16]) y = np.sqrt(np.abs(x)) * np.sign(x) # [-1, 1, 10, 4, -10, -4] 
+11
source

All Articles