-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcomplex_numbers.py
64 lines (55 loc) · 1.92 KB
/
complex_numbers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# Author: Bojan G. Kalicanin
# Date: 19-Nov-2016
# One line of input: The real and imaginary part of a number separated
# by a space.
from math import sqrt
class ComplexNumber(object):
"""Representation of the complex number."""
def __init__(self, x=0, y=0):
self.real_p = x
self.imag_p = y
def __add__(self, other):
"""Overloading addition operator."""
s = ComplexNumber()
s.real_p = self.real_p + other.real_p
s.imag_p = self.imag_p + other.imag_p
return s
def __sub__(self, other):
"""Overloading subtraction operator."""
s = ComplexNumber()
s.real_p = self.real_p - other.real_p
s.imag_p = self.imag_p - other.imag_p
return s
def __mul__(self, other):
"""Overloading multiplication operator."""
s = ComplexNumber()
s.real_p = self.real_p*other.real_p - self.imag_p*other.imag_p
s.imag_p = self.real_p*other.imag_p + self.imag_p*other.real_p
return s
def __truediv__(self, other):
"""Overloading division operator."""
s = ComplexNumber()
s.real_p = (self.real_p*other.real_p + self.imag_p*other.imag_p) / (other.real_p**2 + other.imag_p**2)
s.imag_p = (self.imag_p*other.real_p - self.real_p*other.imag_p) / (other.real_p**2 + other.imag_p**2)
return s
def __abs__(self):
"""Overloading modulus operator."""
s = ComplexNumber()
s.real_p = sqrt(self.real_p**2 + self.imag_p**2)
return s
def __str__(self):
if self.imag_p >= 0:
s = "{0:.2f}+{1:.2f}i".format(self.real_p, self.imag_p)
else:
s = "{0:.2f}{1:.2f}i".format(self.real_p, self.imag_p)
return s
x1, y1 = map(float, input().split())
x2, y2 = map(float, input().split())
z1 = ComplexNumber(x1, y1)
z2 = ComplexNumber(x2, y2)
print(z1+z2)
print(z1-z2)
print(z1*z2)
print(z1/z2)
print(abs(z1))
print(abs(z2))