Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Square root of all values in numpy array, preserving sign

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.

like image 887
sawyer Avatar asked Jul 07 '15 23:07

sawyer


People also ask

How do you square root all elements in a NumPy array?

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.

Does NumPy have square root?

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.

How do I get the NumPy sign of a number?

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.

Can you square a NumPy array?

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.


1 Answers

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]
like image 144
drglove Avatar answered Sep 21 '22 23:09

drglove