-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathequations.py
More file actions
79 lines (66 loc) · 2.72 KB
/
equations.py
File metadata and controls
79 lines (66 loc) · 2.72 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
72
73
74
75
76
77
78
79
# equations.py
from sympy import symbols, Eq, solve, sympify, SympifyError
from utils import show_error
def solve_single_equation(equation_str, var_name="x"):
try:
x = symbols(var_name)
if '=' in equation_str:
lhs_str, rhs_str = equation_str.split('=', 1)
lhs = sympify(lhs_str)
rhs = sympify(rhs_str)
equation = Eq(lhs, rhs)
else:
equation = sympify(equation_str)
solutions = solve(equation, x)
if not solutions:
return "No solution exists."
elif len(solutions) == 1:
return f"x = {solutions[0]}"
else:
return f"Solutions: {', '.join(str(sol) for sol in solutions)}"
except SympifyError:
show_error("Invalid equation format. (e.g., x**2 - 4 = 0, abs(x) = 5, sin(x) = 1)")
return None
except Exception as e:
show_error(f"An error occurred during equation solving: {e}")
return None
def solve_system_of_equations(equations_str, var_names_str):
try:
var_symbols = symbols(var_names_str)
if not isinstance(var_symbols, tuple):
var_symbols = (var_symbols,)
equation_list = []
for eq_str in equations_str.split(';'):
eq_str = eq_str.strip()
if not eq_str:
continue
if '=' in eq_str:
lhs_str, rhs_str = eq_str.split('= 정', 1)
lhs = sympify(lhs_str)
rhs = sympify(rhs_str)
equation_list.append(Eq(lhs, rhs))
else:
show_error(f"Equation '{eq_str}' is not in 'LHS=RHS' format.")
return None
if not equation_list:
show_error("No valid equations found for the system.")
return None
solutions = solve(equation_list, var_symbols)
if not solutions:
return "No solution exists for the system."
if isinstance(solutions, dict):
return "Solution: " + ", ".join(f"{k}={v}" for k, v in solutions.items())
elif isinstance(solutions, list) and all(isinstance(s, dict) for s in solutions):
formatted_solutions = []
for sol_dict in solutions:
formatted_solutions.append("{" + ", ".join(f"{k}={v}" for k, v in sol_dict.items()) + "}")
return "Solutions: " + "; ".join(formatted_solutions)
else:
return f"Solutions: {solutions}"
except SympifyError:
show_error(
"Invalid equation or variable format for system solving. Separate equations with ';'. (e.g., x+y=5; x-y=1)")
return None
except Exception as e:
show_error(f"An error occurred during system solving: {e}")
return None