import sympy as sp import numpy as np import matplotlib.pyplot as plt x, y = sp.symbols('x y') def generate_polynomial_template(degree): terms = [f"a{i}*x^{degree - i}" for i in range(degree)] + [f"a{degree}"] return " + ".join(terms) + " = 0" def solve_polynomial(degree, coeff_string): try: coeffs = [sp.sympify(s) for s in coeff_string.strip().split()] if len(coeffs) != degree + 1: return f"⚠️ Please enter exactly {degree + 1} coefficients.", None, None, "" poly = sum([coeffs[i] * x**(degree - i) for i in range(degree + 1)]) simplified = sp.simplify(poly) # Step-by-step factorization factored_steps = [] current_expr = simplified while True: factored = sp.factor(current_expr) if factored == current_expr: break factored_steps.append(factored) current_expr = factored roots = sp.solve(sp.Eq(simplified, 0), x) root_display = [] for i, r in enumerate(roots): r_simplified = sp.nsimplify(r, rational=True) root_display.append(f"r_{{{i+1}}} = {sp.latex(r_simplified)}") steps_output = f"### 🧐 Polynomial Expression\n\n$$ {sp.latex(poly)} = 0 $$\n\n" steps_output += f"### ✏️ Simplified\n\n$$ {sp.latex(simplified)} = 0 $$\n\n" if factored_steps: steps_output += "### 🪜 Step-by-Step Factorization\n\n" for i, step in enumerate(factored_steps, 1): steps_output += f"**Step {i}:** $$ {sp.latex(step)} = 0 $$\n\n" else: steps_output += "### 🤷 No further factorization possible\n\n" steps_output += "### 🥮 Roots\n\n$$ " + " \\quad ".join(root_display) + " $$" # Plotting f_lambdified = sp.lambdify(x, simplified, modules=["numpy"]) x_vals = np.linspace(-10, 10, 400) y_vals = f_lambdified(x_vals) fig, ax = plt.subplots(figsize=(6, 4)) ax.plot(x_vals, y_vals, label="Polynomial") ax.axhline(0, color='black', linewidth=0.5) ax.axvline(0, color='black', linewidth=0.5) ax.set_title("📈 Graph of the Polynomial") ax.set_xlabel("x") ax.set_ylabel("f(x)") ax.grid(True) real_roots = [sp.N(r.evalf()) for r in roots if sp.im(r) == 0] for r in real_roots: ax.plot([float(r)], [0], 'ro', label="Real Root") ax.legend() return steps_output, fig, "", steps_output except Exception as e: return f"❌ Error: {e}", None, "", "" def solve_linear_system(eq1_str, eq2_str): try: eq1 = sp.sympify(eq1_str) eq2 = sp.sympify(eq2_str) sol = sp.solve((eq1, eq2), (x, y), dict=True) steps = "### 🔍 Solving System\n\n" steps += f"**Equation 1:** $$ {sp.latex(eq1)} $$\n\n" steps += f"**Equation 2:** $$ {sp.latex(eq2)} $$\n\n" if sol: sol = sol[0] steps += f"**Solution:** $$ x = {sp.latex(sol[x])}, \\quad y = {sp.latex(sol[y])} $$\n\n" else: steps += "**❌ No unique solution or inconsistent system**\n" # Plotting x_vals = np.linspace(-10, 10, 400) f1 = sp.solve(eq1, y) f2 = sp.solve(eq2, y) fig, ax = plt.subplots(figsize=(6, 4)) if f1 and f2: y1_vals = sp.lambdify(x, f1[0], modules=["numpy"])(x_vals) y2_vals = sp.lambdify(x, f2[0], modules=["numpy"])(x_vals) ax.plot(x_vals, y1_vals, label="Equation 1") ax.plot(x_vals, y2_vals, label="Equation 2") if sol: px = float(sp.N(sol[x])) py = float(sp.N(sol[y])) ax.plot(px, py, 'ro') ax.annotate(f"({px:.2f}, {py:.2f})", (px, py), textcoords="offset points", xytext=(10, 5), ha='center', color='red') ax.axhline(0, color='black', linewidth=0.5) ax.axvline(0, color='black', linewidth=0.5) ax.set_title("📉 Graph of the Linear System") ax.set_xlabel("x") ax.set_ylabel("y") ax.grid(True) ax.legend() return steps, fig, steps except Exception as e: return f"❌ Error: {e}", None, ""