-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomplex_numbers.py
More file actions
71 lines (65 loc) · 2.18 KB
/
complex_numbers.py
File metadata and controls
71 lines (65 loc) · 2.18 KB
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
65
66
67
68
69
70
71
# complex_numbers.py
from sympy import I, sympify, SympifyError, sqrt
from utils import show_error
def complex_add(z1_str, z2_str):
try:
z1 = sympify(z1_str)
z2 = sympify(z2_str)
result = z1 + z2
return f"({z1_str}) + ({z2_str}) = {result}"
except SympifyError:
show_error("Invalid complex number format. (e.g., 2+3*I, 5)")
return None
except Exception as e:
show_error(f"An error occurred during addition: {e}")
return None
def complex_subtract(z1_str, z2_str):
try:
z1 = sympify(z1_str)
z2 = sympify(z2_str)
result = z1 - z2
return f"({z1_str}) - ({z2_str}) = {result}"
except SympifyError:
show_error("Invalid complex number format. (e.g., 2+3*I, 5)")
return None
except Exception as e:
show_error(f"An error occurred during subtraction: {e}")
return None
def complex_multiply(z1_str, z2_str):
try:
z1 = sympify(z1_str)
z2 = sympify(z2_str)
result = (z1 * z2).expand()
return f"({z1_str}) * ({z2_str}) = {result}"
except SympifyError:
show_error("Invalid complex number format. (e.g., 2+3*I, 5)")
return None
except Exception as e:
show_error(f"An error occurred during multiplication: {e}")
return None
def complex_divide(z1_str, z2_str):
try:
z1 = sympify(z1_str)
z2 = sympify(z2_str)
if z2 == 0:
show_error("Cannot divide by zero.")
return None
result = (z1 / z2).simplify()
return f"({z1_str}) / ({z2_str}) = {result}"
except SympifyError:
show_error("Invalid complex number format. (e.g., 2+3*I, 5)")
return None
except Exception as e:
show_error(f"An error occurred during division: {e}")
return None
def complex_magnitude(z_str):
try:
z = sympify(z_str)
magnitude = abs(z)
return f"Magnitude of {z_str} = {magnitude}"
except SympifyError:
show_error("Invalid complex number format. (e.g., 2+3*I, 5)")
return None
except Exception as e:
show_error(f"An error occurred during magnitude calculation: {e}")
return None