[Tutor] Complex roots

Tim Peters tim.peters at gmail.com
Sat Dec 11 05:45:00 CET 2004


[Dick Moores]
> Aw, that's just amazing.

Well, complex numbers are amazing in many ways.  The code is actually
obvious, if you understand the motivation.  Polar coordinates are more
natural for complex * /  and **.  If you a view a complex number c as
a vector in the complex plane (from the origin to c), then c's n'th
roots are just n equally spaced spokes on a wheel, with one of the
spokes coinciding with c's "natural" angle divided by n.  That
determines the angles of all the spokes, since there are n spokes
altogether and the angular difference between adjacent spokes is
constant (2*pi/n).  All the seeming obscurity in the code is really
just due to converting between rectangular (x, y) and polar (length,
angle) representations.

If we worked with polar coordinates all along, the input would be
given as a magnitude and angle, say r and a.  The n n'th roots then
(still in polar coordinates) all have magnitude r**(1./n), and the n
angles are a/n, a/n + b, a/n + 2*b, ..., and a/n + (n-1)*b where
b=2*pi/n.  Piece o' cake!

> I put your function in http://www.rcblue.com/Python/croots.py, 

That's fine by me -- but I'd appreciate it if you stopped claiming
there that my name is Bill <wink>.

...

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

I don't, no.  You can code one for cubics from Cardano's formula, e.g.,

    http://mathworld.wolfram.com/CubicFormula.html
 
but it's rarely worth the bother -- it's complicated and doesn't
generalize.  In practice, roots for polynomials beyond quadratics are
usually obtained by numerical approximation methods that don't care
much about the polynomial's degree.


More information about the Tutor mailing list