# # Complex number manipulation # # Matt Bishop, ECS 36A, Fall 2019 # import copy # # defining complex numbers # class Mycomplex: # create it def __init__(self, r, i): self.real = r self.imag = i # generate a string form def __str__(self): if self.imag < 0: return str(self.real) + str(self.imag) + "i" else: return str(self.real) + "+" + str(self.imag) + "i" # some arithmetic operators def __add__(self, a): return Mycomplex(self.real + a.real, self.imag + a.imag) def __sub__(self, a): return Mycomplex(self.real - a.real, self.imag - a.imag) def __mul__(self, a): return Mycomplex(self.real * a.real - self.imag * a.imag, self.real * a.imag + self.imag * a.real) # some comparison operators def __lt__(self, a): return self.real < a.real and self.imag < a.imag def __eq__(self, a): return self.real == a.real and self.imag == a.imag def __gt__(self, a): return self.real > a.real and self.imag > a.imag # # Here we use everything; first, create numbers # x1 and x2 are comparable; x3 is not # print("--------------------------------------------------") print("Generate 3 complex numbers:") x1 = Mycomplex(3, 4) x2 = Mycomplex(-3, -2) x3 = Mycomplex(-5, 6) print("x1 = "+str(x1)+", x2 ="+str(x2)+", x3 = "+str(x3)) # demonstrate the arithmetic operations print("--------------------------------------------------") print("Add x1 and x2:") x4 = x1 + x2 print("x4 = x1 + x2 =", str(x4)) print("Subtract x3 from x2:") x5 = x2 - x3 print("x5 = x2 - x3 =", str(x5)) print("Multiply x1 and x3:") x6 = x1 * x3 print("x6 = x1 * x3 =", str(x6)) # demonstrate comparison operators print("--------------------------------------------------") print("Comparing x2 and x1:") print("x2 < x1:", x2 < x1) print("x2 == x1:", x2 == x1) print("x2 > x1:", x2 > x1) print("--------------------------------------------------") print("Comparing x3 and x1:") print("x3 < x1:", x3 < x1) print("x3 == x1:", x3 == x1) print("x3 > x1:", x3 > x1) # demonstrate assignment print("--------------------------------------------------") print("Now we do assignment") x1 = Mycomplex(3, 4) x5 = x1 print("x1 =", x1, "and x5 =", x5) print("Now we reset an attribute of x1") x1.real = 5 print("x1 =", x1, "and x5 =", x5) # demonstrate shallow copoies print("--------------------------------------------------") print("Now we do copy") x1 = Mycomplex(3, 4) x5 = copy.copy(x1) print("x1 =", x1, "and x5 =", x5) print("Now we reset an attribute of x1") x1.real = 5 print("x1 =", x1, "and x5 =", x5)