简体   繁体   中英

Cube roots of a complex number in python

How do I calculate the cube roots of a complex number in python? Currently, the only way I've found to do it is according to this answer, but I'm trying to remove any and all import statements from my code.


Current method, reproduced here:

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 ]

Compute one and multiply with the cube roots of 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]

Test:

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

Doing the same with yours is less accurate:

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

Here is an approach using rotation by a factor of i^(2/3) .

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

Python's built-in complex can handle finding one root out of the box:

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

Examples:

cube_root(-3)
(0.7211247851537043+1.2490247664834064j)

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

The function you reproduced above is one way to get all three roots.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM