|
| 1 | +import math |
| 2 | + |
| 3 | + |
| 4 | +class Complex(object): |
| 5 | + def __init__(self, real, imaginary): |
| 6 | + self.real = real |
| 7 | + self.imaginary = imaginary |
| 8 | + |
| 9 | + def __add__(self, other): |
| 10 | + return Complex(self.real + other.real, self.imaginary + other.imaginary) |
| 11 | + |
| 12 | + def __sub__(self, other): |
| 13 | + return Complex(self.real - other.real, self.imaginary - other.imaginary) |
| 14 | + |
| 15 | + def __mul__(self, other): |
| 16 | + return Complex( |
| 17 | + self.real * other.real - self.imaginary * other.imaginary, |
| 18 | + self.real * other.imaginary + self.imaginary * other.real |
| 19 | + ) |
| 20 | + |
| 21 | + def __truediv__(self, other): |
| 22 | + other_mod_2 = other.mod_square() |
| 23 | + answer = Complex(self.real / other_mod_2, self.imaginary / other_mod_2) * other.conjugate() |
| 24 | + return Complex(round(answer.real, 2), round(answer.imaginary, 2)) |
| 25 | + |
| 26 | + def mod(self): |
| 27 | + return Complex(round(math.sqrt(self.mod_square()), 2), 0.00) |
| 28 | + |
| 29 | + def mod_square(self): |
| 30 | + return round(self.real * self.real + self.imaginary * self.imaginary, 2) |
| 31 | + |
| 32 | + def conjugate(self): |
| 33 | + return Complex(self.real, -self.imaginary) |
| 34 | + |
| 35 | + def __str__(self): |
| 36 | + if self.imaginary == 0: |
| 37 | + result = "%.2f+0.00i" % (self.real) |
| 38 | + elif self.real == 0: |
| 39 | + if self.imaginary >= 0: |
| 40 | + result = "0.00+%.2fi" % (self.imaginary) |
| 41 | + else: |
| 42 | + result = "0.00-%.2fi" % (abs(self.imaginary)) |
| 43 | + elif self.imaginary > 0: |
| 44 | + result = "%.2f+%.2fi" % (self.real, self.imaginary) |
| 45 | + else: |
| 46 | + result = "%.2f-%.2fi" % (self.real, abs(self.imaginary)) |
| 47 | + return result |
| 48 | + |
| 49 | + |
| 50 | +if __name__ == '__main__': |
| 51 | + c = map(float, input().split()) |
| 52 | + d = map(float, input().split()) |
| 53 | + x = Complex(*c) |
| 54 | + y = Complex(*d) |
| 55 | + print(*map(str, [x+y, x-y, x*y, x/y, x.mod(), y.mod()]), sep='\n') |
0 commit comments