[Tutor] Complex roots

Dick Moores rdm at rcblue.com
Fri Dec 10 11:15:57 CET 2004


Aw, that's just amazing.

I put your function in http://www.rcblue.com/Python/croots.py, which gets 
c and n from user and adds a test function.

Here's what one run produces:

====================================
Enter either a complex number in form x + yj, or a real number: 3.1 -1j
Enter an integer n, to find the n'th roots: 5
c is (3.1-1j); n is 5

root1 is (1.26393645827-0.0789828505298j)
root1 to the 5 power is (3.1-1j)

root2 is (0.465695000088+1.17766796174j)
root2 to the 5 power is (3.1-1j)

root3 is (-0.976121119826+0.806821678349j)
root3 to the 5 power is (3.1-1j)

root4 is (-1.06897102928-0.679024741664j)
root4 to the 5 power is (3.1-1j)

root5 is (0.315460690744-1.2264820479j)
root5 to the 5 power is (3.1-1j)
======================================

Actually, I'm trying to write a Python script that computes all 3 roots 
of a cubic equation. Do you happen to have one tucked away in your store 
of wisdom and tricks? (One for real coefficients will do).

Anyway, thought it wouldn't hurt to ask..

Dick

Tim Peters wrote at 07:41 12/9/2004:
>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