[Tutor] Little problem with math module
Terry Carroll
carroll at tjc.com
Thu May 22 07:29:36 CEST 2008
On Wed, 21 May 2008, Terry Carroll wrote:
> The following (barely-tested) routine should calculate all the Nth roots
> of a given x, even when x is negative and N is even:
I realize I'm probably talking to myself here, but for the benefit of the
archives, I found a more elegant approach after reading
http://everything2.com/node/1309141. The following routine instead uses
the formula at the end of the page (although I must admit I needed to read
the entire page very carefully before I actually understood it):
def nthroots(x,n):
"""returns a list of all nth roots of x;
see http://everything2.com/node/1309141 """
from math import atan2, pi
from cmath import exp
i = 0+1j
z=complex(x)
# express the cartesian (x+yi) complex number z
# as polar (modulus R & argument theta)
R = abs(z)
theta = atan2(z.imag, z.real)
coef = R**(1.0/n)
return [coef * exp(i*(theta/n + 2*pi*k/n)) for k in range(0,n)]
I'm not sure it's faster than the method from the prior email, but it
certainly seems a bit less ham-handed. It could probably be sped up, at
the cost of some obfuscation, by pulling a few more things out of the list
comprehension, e.g.,
X = i*theta/n
Y = (0+2j)*pi/n
return [coeff * exp(X + Y*k) for k in range(0,n)]
More information about the Tutor
mailing list