# # Complex number manipulation # # Matt Bishop, MHI 289I, Fall 20242 # import copy # # defining complex numbers (a + bi, where i = sqrt(-1); # here we use r for the real part rather than a, and we # use i for the imaginary part rather than b) # 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("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)) print("--------------------------------------------------") input("Press ENTER to continue") # demonstrate the arithmetic operations print("\nAdd 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)) print("--------------------------------------------------") input("Press ENTER to continue") # demonstrate comparison operators print("\nComparing 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) print("--------------------------------------------------") input("Press ENTER to continue") # demonstrate assignment print("\nNow 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) print("--------------------------------------------------") input("Press ENTER to continue") # demonstrate shallow copoies print("\nNow 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)