Numpy n-th odd root including negative values

六眼飞鱼酱① 提交于 2021-01-27 07:07:01

问题


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)
>>> array([-4.64158883, -4.26859722, -3.81571414, -3.21829795, -2.23144317,
    2.23144317,  3.21829795,  3.81571414,  4.26859722,  4.64158883])

However, if I want to compute the same thing for other k-th odd roots in a straightforward manner I'm somewhat stuck. I cannot use np.power directly, not even to compute the cube root:

np.power(x,1./3)
>>> array([       nan,        nan,        nan,        nan,        nan,
   2.23144317, 3.21829795, 3.81571414, 4.26859722, 4.64158883])

(-100.)**(1./3)
>>> ValueError: negative number cannot be raised to a fractional power

I could compute the k-th odd root for the absolute values of x and then change the sign accordingly for the negative entries in x, but I am wondering if there is a more straightforward way. Here is my current solution:

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)

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])

回答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])


来源:https://stackoverflow.com/questions/50491326/numpy-n-th-odd-root-including-negative-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!