python 中复数的立方根

Cube roots of a complex number in python

如何计算 python 中复数的立方根?目前,我发现的唯一方法是根据 this 答案,但我试图从我的代码中删除所有 import 语句。


当前方法,转载于此:

import math
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 ]

Python 的内置 complex 可以立即找到一个根:

def cube_root(v):
    if not isinstance(v, complex):
        v = complex(v, 0)
    return v ** (1.0 / 3.0)

示例:

cube_root(-3)
(0.7211247851537043+1.2490247664834064j)

cube_root(complex(1, -2))
(1.2196165079717578-0.47171126778938893j)

您在上面复制的函数是获得所有三个根的一种方法。

计算 1 并乘以 1 的立方根?

cuberoots_of_1 = 1, complex(-.5, .75**.5), complex(-.5, -.75**.5)

def cuberoot(z):
    cuberoot = complex(z)**(1/3)
    return [cuberoot * cr1 for cr1 in cuberoots_of_1]

测试:

>>> cuberoot(-2 + 3j)
[(1.1532283040274223+1.0106429470939737j),
 (-1.4518566183526649+0.49340353410400484j),
 (0.2986283143252425-1.5040464811979786j)]

>>> for z in cuberoot(-2 + 3j):
        print(z**3, abs(z**3 - (-2 + 3j)))

(-1.999999999999999+3j) 1.1102230246251565e-15
(-1.999999999999999+3j) 1.1102230246251565e-15
(-1.9999999999999982+2.9999999999999996j) 1.831026719408895e-15

用你的方法做同样的事情不太准确:

(-1.999999999999996+3.000000000000002j) 4.572178254219406e-15
(-1.9999999999999933+3.000000000000004j) 7.768388458966724e-15
(-1.9999999999999956+3.0000000000000013j) 4.636427468134552e-15

这是一种使用 i^(2/3) 因子旋转的方法。

f = 1j**(2/3)
def cube_roots(z):
  r = z**(1/3)
  return [r, -r*f, r*f**2]