[Tutor] Complex roots

Dick Moores rdm at rcblue.com
Fri Dec 10 16:38:06 CET 2004


I've modified croots.py to croots2.py 
(<http://www.rcblue.com/Python/croots2.py>)

The only changes are in the testCrootsResult function. It will ignore 
very small .imag or .real when printing.

Thus this result:
================================
Enter either a complex number in form x + yj, or a real number: 4
Enter an integer n, to find the n'th roots of that number: 3
c is (4+0j); n is 3

root1 is 1.58740105197, adjusted from (1.58740105197+0j)
root1 to the 3 power is 4.0, adjusted from (4+0j)

root2 is (-0.793700525984+1.374729637j)
root2 to the 3 power is 4.0, adjusted from (4-2.6645352591e-015j)

root3 is (-0.793700525984-1.374729637j)
root3 to the 3 power is 4.0, adjusted from (4-5.55111512313e-015j)
====================================

Dick

Dick Moores wrote at 02:15 12/10/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