You are viewing a single comment's thread. Return to all comments →
class Complex(object): def __init__(self, real, imaginary): self.r = real self.im = imaginary def __add__(self, no): sum_r = self.r + no.r sum_im = self.im + no.im return Complex(sum_r, sum_im) def __sub__(self, no): sub_r = self.r - no.r sub_im = self.im - no.im return Complex(sub_r, sub_im) def __mul__(self, no): mul_r = self.r * no.r + self.im * no.im * -1 mul_im = self.r * no.im + self.im * no.r return Complex(mul_r, mul_im) def __truediv__(self, no): div_r = (self.r * no.r + self.im * no.im) / (no.r ** 2 + no.im ** 2) div_im = (no.r * self.im - no.im * self.r) / (no.r ** 2 + no.im ** 2) return Complex(div_r, div_im) def mod(self): temp = (self.r ** 2 + self.im ** 2) ** (1 / 2) return Complex(temp, 0) def __str__(self): return f"{self.r:.2f}{'+' if self.im >= 0 else ''}{self.im:.2f}i"
Seems like cookies are disabled on this browser, please enable them to open this website
Classes: Dealing with Complex Numbers
You are viewing a single comment's thread. Return to all comments →