有人可以帮我找到如何使用python计算负数的立方根的解决方案吗?
>>> math.pow(-3, float(1)/3)
nan
Run Code Online (Sandbox Code Playgroud)
这是行不通的.负数的立方根是负数.有解决方案吗
And*_*ker 18
简单地使用De Moivre的公式,足以表明值的立方根,无论符号如何,都是一个多值函数.这意味着,对于任何输入值,将有三种解决方案.迄今为止提出的大多数解决方案仅返回原则根.返回所有有效根,并明确测试非复杂特殊情况的解决方案如下所示.
import numpy
import math
def cuberoot( z ):
z = complex(z)
x = z.real
y = z.imag
mag = abs(z)
arg = math.atan2(y,x)
return [ mag**(1./3) * numpy.exp( 1j*(arg+2*n*math.pi)/3 ) for n in range(1,4) ]
Run Code Online (Sandbox Code Playgroud)
编辑:根据要求,在不适合依赖numpy的情况下,以下代码执行相同的操作.
def cuberoot( z ):
z = complex(z)
x = z.real
y = z.imag
mag = abs(z)
arg = math.atan2(y,x)
resMag = mag**(1./3)
resArg = [ (arg+2*math.pi*n)/3. for n in range(1,4) ]
return [ resMag*(math.cos(a) + math.sin(a)*1j) for a in resArg ]
Run Code Online (Sandbox Code Playgroud)
Dav*_*vid 11
math.pow(abs(x),float(1)/3) * (1,-1)[x<0]
Run Code Online (Sandbox Code Playgroud)
DrA*_*rAl 10
你可以使用:
-math.pow(3, float(1)/3)
Run Code Online (Sandbox Code Playgroud)
或者更一般地说:
if x > 0:
return math.pow(x, float(1)/3)
elif x < 0:
return -math.pow(abs(x), float(1)/3)
else:
return 0
Run Code Online (Sandbox Code Playgroud)
把早期的答案变成一个单行:
import math
def cubic_root(x):
return math.copysign(math.pow(abs(x), 1.0/3.0), x)
Run Code Online (Sandbox Code Playgroud)
您可以使用以下方法获得完整(所有n根)和更一般(任何符号,任何功率)解决方案:
import cmath
x, t = -3., 3 # x**(1/t)
a = cmath.exp((1./t)*cmath.log(x))
p = cmath.exp(1j*2*cmath.pi*(1./t))
r = [a*(p**i) for i in range(t)]
Run Code Online (Sandbox Code Playgroud)
说明:a使用等式x u = exp(u*log(x)).然后,该解决方案将成为其中一个根,并且为了获得其他解决方案,将其在复平面中旋转(完全旋转)/ t.