Skip to content Skip to sidebar Skip to footer

Numpy N-th Odd Root Including Negative Values

I want to calculate the n-th odd root of some numbers in python. Numpy as a cube root function. Using that function I can compute x^(1/3). x = np.linspace(-100,100,100) np.cbrt(x)

Solution 1:

I'm going to respond to my own question with my current solution. This is not to say that there doesn't exist an easier or faster method.

def kth_root(x,k):
    if k % 2 != 0:
        res = np.power(np.abs(x),1./k)
        return res*np.sign(x)
    else:
        return np.power(np.abs(x),1./k)


x = np.linspace(-100,100,100)
kth_root(x,3)
>>> array([-4.64158883, -4.26859722, -3.81571414, -3.21829795, -2.23144317,
2.23144317,  3.21829795,  3.81571414,  4.26859722,  4.64158883])

Solution 2:

I had a similar issue and, starting from you def a defined a function to compute x to the power of rational exponent n/d with the correct real domain.

defr_pow(x, n, d):
    """
    Compute x to the power of n/d (not reduced to lowest
    expression) with the correct function real domains.
    
    ARGS:
        x (int,float,array): base
        n (int)            : exponent numerator
        d (int)            : exponent denominator
        
    RETURNS:
        x to the power of n/d
    """# list to arrayiftype(x) == list:
        x = np.array(x)
    # check inputsiftype(n) != intortype(d) != int:
        raise Exception("Exponent numerator and denominator must be integers")
    # if denominator is zeroifnot d:
        raise Exception("Exponent denominator cannot be 0")
        
    # raise x to power of n
    X = x**n
    # even denominatorifnot d % 2:
        # domain is for X>=0 onlyiftype(x) == np.ndarray:
            X[X<0] = np.nan
        elif X < 0:
            X = np.nan
        res = np.power(X, 1./d)
        return res
    # odd denominatorelse:
        # domain is all R
        res = np.power(np.abs(X), 1./d)
        res *= np.sign(X)
        return res

So, for example, we can have x^(2/3), where the domain is all R and the function sign is always positive (because x^2 is always positive)

x = np.linspace(-10, 10, 1000)
plt.plot(x, r_pow(x, 2, 3));

enter image description here

or x^(1/3) where the domain is all R, but the function sign is negative for x<0

x = np.linspace(-10, 10, 1000)
plt.plot(x, r_pow(x, 1, 3));

enter image description here

or x^(1/6) where the real domain is [0, +∞)

x = np.linspace(-10, 10, 1000)
plt.plot(x, r_pow(x, 1, 6));

enter image description here

Post a Comment for "Numpy N-th Odd Root Including Negative Values"