import math

# Klassen Complex representerar komplexa tal med rektangulära koordinater
class Complex (object):
    def __init__ (self, re, im):
        self.re = re
        self.im = im

    def __str__ (self):
        return "%g+%gi" % (self.re, self.im)

    def __lt__ (self, other):
        return magnitude (self) < magnitude (other)

    def __add__ (self, other):
        return Complex (self.re + other.re, self.im + other.im)

# Komplex division
#
# Parametrar:
# x: täljare (komplext tal)
# y: nämnare (komplext tal)
#
# Returnerar kvoten x / y (komplext tal)
#
def div (x, y):
    return polarToRect (magnitude (x) / magnitude (y), argument (x) - argument (y))

# Följande funktioner hanterar representationen av komplexa tal

# Komplex magnitud
#
# c: Komplext tal
#
# Returnerar den komplexa magnituden |c|
#
def magnitude (c):
    return math.sqrt (c.re * c.re + c.im * c.im)

# Argument
#
# c: Komplext tal
#
# Returnerar arg (c)
#
def argument (c):
    return math.atan (c.im / c.re)

# Omvandling från polär till rektangulär representation
#
# magnitude: Komplex magnitud
# argument: Komplex fas (argumentet hos ett komplext tal)
#
# Returnerar motsvarande komplexa tal som objekt av typen Complex
#
def polarToRect (magnitude, argument):
    return Complex (magnitude * math.cos (argument),
                    magnitude * math.sin (argument))
