问题
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