Numpy 第 n 个奇数根,包括负值 [英] Numpy n-th odd root including negative values
问题描述
我想在python中计算一些数字的第n个奇数根.Numpy 作为立方根函数.使用该函数我可以计算 x^(1/3).
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])
然而,如果我想以一种直接的方式为其他第 k 个奇数根计算同样的东西,我有点卡住了.我不能直接使用 np.power,甚至不能计算立方根:
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
我可以计算 x 的绝对值的第 k 个奇数根,然后相应地更改 x 中负条目的符号,但我想知道是否有更直接的方法.这是我目前的解决方案:
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])
推荐答案
我将用我当前的解决方案来回答我自己的问题.这并不是说不存在更简单或更快的方法.
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])
这篇关于Numpy 第 n 个奇数根,包括负值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!