[Tutor] Complex roots

Tim Peters tim.peters at gmail.com
Thu Dec 9 16:41:52 CET 2004

[Dick Moores]
> VERY helpful, Matt. Thanks.
> One question: This seems to not compute accurately at all
> when the imaginary part of number=complex() is other than 0.

That's just because the math was wrong <wink>.  Starting with theta =
0.0 *assumed* the imaginary part is 0, although I can't guess whether
that was by accident or design.

Try this instead:

def croots(c, n):
    """Return list of the n n'th roots of complex c."""
    from math import sin, cos, atan2, pi

    arg = abs(c)**(1.0/n)
    theta = atan2(c.imag, c.real)
    result = []
    for i in range(n):
        theta2 = (theta + 2*pi*i)/n
        x = arg * cos(theta2)
        y = arg * sin(theta2)
        result.append(complex(x, y))
    return result

More information about the Tutor mailing list