# croots.py # the croots() function is by Tim Peters of the tutors list and much other fame def getComplexNumberFromUser(): c = raw_input("Enter either a complex number in form x + yj, or a real number: ") if "j" not in c: c = eval(c + "+0j") else: c = eval(c) n = int(raw_input("Enter an integer n, to find the n'th roots of that number: ")) print "c is %s; n is %d" % (c,n) return c, n 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 def testCrootsResult(rootsList): power = len(rootsList) for i in range(power): print "root%d is %s" % (i+1,rootsList[i]) print "root%d to the %d power is %s" % (i+1,power, rootsList[i]**power) print c, n = getComplexNumberFromUser() rootsList = croots(c, n) print testCrootsResult(rootsList)