Spaces:
Sleeping
Sleeping
Create solver.py
Browse files
solver.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sympy as sp
|
| 2 |
+
import numpy as np
|
| 3 |
+
import matplotlib.pyplot as plt
|
| 4 |
+
|
| 5 |
+
x, y = sp.symbols('x y')
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def generate_polynomial_template(degree):
|
| 9 |
+
terms = [f"a{i}*x^{degree - i}" for i in range(degree)] + [f"a{degree}"]
|
| 10 |
+
return " + ".join(terms) + " = 0"
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def solve_polynomial(degree, coeff_string):
|
| 14 |
+
try:
|
| 15 |
+
coeffs = [sp.sympify(s) for s in coeff_string.strip().split()]
|
| 16 |
+
if len(coeffs) != degree + 1:
|
| 17 |
+
return f"⚠️ Please enter exactly {degree + 1} coefficients.", None, None, ""
|
| 18 |
+
|
| 19 |
+
poly = sum([coeffs[i] * x**(degree - i) for i in range(degree + 1)])
|
| 20 |
+
simplified = sp.simplify(poly)
|
| 21 |
+
|
| 22 |
+
# Step-by-step factorization
|
| 23 |
+
factored_steps = []
|
| 24 |
+
current_expr = simplified
|
| 25 |
+
while True:
|
| 26 |
+
factored = sp.factor(current_expr)
|
| 27 |
+
if factored == current_expr:
|
| 28 |
+
break
|
| 29 |
+
factored_steps.append(factored)
|
| 30 |
+
current_expr = factored
|
| 31 |
+
|
| 32 |
+
roots = sp.solve(sp.Eq(simplified, 0), x)
|
| 33 |
+
root_display = []
|
| 34 |
+
for i, r in enumerate(roots):
|
| 35 |
+
r_simplified = sp.nsimplify(r, rational=True)
|
| 36 |
+
root_display.append(f"r_{{{i+1}}} = {sp.latex(r_simplified)}")
|
| 37 |
+
|
| 38 |
+
steps_output = f"### 🧐 Polynomial Expression\n\n$$ {sp.latex(poly)} = 0 $$\n\n"
|
| 39 |
+
steps_output += f"### ✏️ Simplified\n\n$$ {sp.latex(simplified)} = 0 $$\n\n"
|
| 40 |
+
|
| 41 |
+
if factored_steps:
|
| 42 |
+
steps_output += "### 🪜 Step-by-Step Factorization\n\n"
|
| 43 |
+
for i, step in enumerate(factored_steps, 1):
|
| 44 |
+
steps_output += f"**Step {i}:** $$ {sp.latex(step)} = 0 $$\n\n"
|
| 45 |
+
else:
|
| 46 |
+
steps_output += "### 🤷 No further factorization possible\n\n"
|
| 47 |
+
|
| 48 |
+
steps_output += "### 🥮 Roots\n\n$$ " + " \\quad ".join(root_display) + " $$"
|
| 49 |
+
|
| 50 |
+
# Plotting
|
| 51 |
+
f_lambdified = sp.lambdify(x, simplified, modules=["numpy"])
|
| 52 |
+
x_vals = np.linspace(-10, 10, 400)
|
| 53 |
+
y_vals = f_lambdified(x_vals)
|
| 54 |
+
|
| 55 |
+
fig, ax = plt.subplots(figsize=(6, 4))
|
| 56 |
+
ax.plot(x_vals, y_vals, label="Polynomial")
|
| 57 |
+
ax.axhline(0, color='black', linewidth=0.5)
|
| 58 |
+
ax.axvline(0, color='black', linewidth=0.5)
|
| 59 |
+
ax.set_title("📈 Graph of the Polynomial")
|
| 60 |
+
ax.set_xlabel("x")
|
| 61 |
+
ax.set_ylabel("f(x)")
|
| 62 |
+
ax.grid(True)
|
| 63 |
+
|
| 64 |
+
real_roots = [sp.N(r.evalf()) for r in roots if sp.im(r) == 0]
|
| 65 |
+
for r in real_roots:
|
| 66 |
+
ax.plot([float(r)], [0], 'ro', label="Real Root")
|
| 67 |
+
|
| 68 |
+
ax.legend()
|
| 69 |
+
|
| 70 |
+
return steps_output, fig, "", steps_output
|
| 71 |
+
|
| 72 |
+
except Exception as e:
|
| 73 |
+
return f"❌ Error: {e}", None, "", ""
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def solve_linear_system(eq1_str, eq2_str):
|
| 77 |
+
try:
|
| 78 |
+
eq1 = sp.sympify(eq1_str)
|
| 79 |
+
eq2 = sp.sympify(eq2_str)
|
| 80 |
+
|
| 81 |
+
sol = sp.solve((eq1, eq2), (x, y), dict=True)
|
| 82 |
+
|
| 83 |
+
steps = "### 🔍 Solving System\n\n"
|
| 84 |
+
steps += f"**Equation 1:** $$ {sp.latex(eq1)} $$\n\n"
|
| 85 |
+
steps += f"**Equation 2:** $$ {sp.latex(eq2)} $$\n\n"
|
| 86 |
+
|
| 87 |
+
if sol:
|
| 88 |
+
sol = sol[0]
|
| 89 |
+
steps += f"**Solution:** $$ x = {sp.latex(sol[x])}, \\quad y = {sp.latex(sol[y])} $$\n\n"
|
| 90 |
+
else:
|
| 91 |
+
steps += "**❌ No unique solution or inconsistent system**\n"
|
| 92 |
+
|
| 93 |
+
# Plotting
|
| 94 |
+
x_vals = np.linspace(-10, 10, 400)
|
| 95 |
+
f1 = sp.solve(eq1, y)
|
| 96 |
+
f2 = sp.solve(eq2, y)
|
| 97 |
+
|
| 98 |
+
fig, ax = plt.subplots(figsize=(6, 4))
|
| 99 |
+
if f1 and f2:
|
| 100 |
+
y1_vals = sp.lambdify(x, f1[0], modules=["numpy"])(x_vals)
|
| 101 |
+
y2_vals = sp.lambdify(x, f2[0], modules=["numpy"])(x_vals)
|
| 102 |
+
ax.plot(x_vals, y1_vals, label="Equation 1")
|
| 103 |
+
ax.plot(x_vals, y2_vals, label="Equation 2")
|
| 104 |
+
|
| 105 |
+
if sol:
|
| 106 |
+
px = float(sp.N(sol[x]))
|
| 107 |
+
py = float(sp.N(sol[y]))
|
| 108 |
+
ax.plot(px, py, 'ro')
|
| 109 |
+
ax.annotate(f"({px:.2f}, {py:.2f})", (px, py), textcoords="offset points", xytext=(10, 5),
|
| 110 |
+
ha='center', color='red')
|
| 111 |
+
|
| 112 |
+
ax.axhline(0, color='black', linewidth=0.5)
|
| 113 |
+
ax.axvline(0, color='black', linewidth=0.5)
|
| 114 |
+
ax.set_title("📉 Graph of the Linear System")
|
| 115 |
+
ax.set_xlabel("x")
|
| 116 |
+
ax.set_ylabel("y")
|
| 117 |
+
ax.grid(True)
|
| 118 |
+
ax.legend()
|
| 119 |
+
|
| 120 |
+
return steps, fig, steps
|
| 121 |
+
|
| 122 |
+
except Exception as e:
|
| 123 |
+
return f"❌ Error: {e}", None, ""
|