I'd like to take the square root of every value in a numpy array, while preserving the sign of the value (and not returning complex numbers when negative) - a signed square root.
The code below demonstrates the desired functionality w/ lists, but is not taking advantage of numpy's optimized array manipulating superpowers.
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.]
For some context, I'm computing the Hellinger Kernel for [thousands of] image comparisons.
Any smooth way to do this with numpy? Thanks.
When we use a 2D NumPy array as the input, the np. sqrt function simply calculates the square root of every element of the array. The output of the function is simply an array of those calculated square roots, arranged in exactly the same shape as the input array.
Python NumPy module is used to work with multidimensional arrays and matrix manipulations. We can use NumPy sqrt() function to get the square root of the matrix elements.
sign() in Python. numpy. sign(array [, out]) function is used to indicate the sign of a number element-wise. For integer inputs, if array value is greater than 0 it returns 1, if array value is less than 0 it returns -1, and if array value 0 it returns 0.
Python numpy. square() function returns a new array with the element value as the square of the source array elements. The source array remains unchanged.
You can try using the numpy.sign
function to capture the sign, 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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With