|
|
import gradio as gr |
|
|
import numpy as np |
|
|
import matplotlib.pyplot as plt |
|
|
import sympy as sp |
|
|
|
|
|
x = sp.symbols('x') |
|
|
|
|
|
|
|
|
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) |
|
|
|
|
|
|
|
|
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 += f"### 🪜 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 += f"### 🤷 No further factorization possible\n\n" |
|
|
|
|
|
steps_output += "### 🥮 Roots\n\n$$ " + " \\quad ".join(root_display) + " $$" |
|
|
|
|
|
|
|
|
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.grid(True) |
|
|
ax.set_title("📈 Graph of the Polynomial") |
|
|
ax.set_xlabel("x") |
|
|
ax.set_ylabel("f(x)") |
|
|
|
|
|
|
|
|
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, "" |
|
|
|
|
|
except Exception as e: |
|
|
return f"❌ Error: {e}", None, "" |
|
|
|
|
|
|
|
|
def update_template(degree): |
|
|
return generate_polynomial_template(degree) |
|
|
|
|
|
with gr.Blocks() as demo: |
|
|
gr.Markdown("## 🔢 Polynomial Solver with Step-by-Step Factorization and Graph") |
|
|
|
|
|
with gr.Row(): |
|
|
degree_slider = gr.Slider(1, 8, value=3, step=1, label="Degree of Polynomial") |
|
|
template_display = gr.Textbox(label="Polynomial Template (Fill in Coefficients)", interactive=False) |
|
|
|
|
|
coeff_input = gr.Textbox(label="Enter Coefficients (space-separated, supports pi, e, sqrt(2), I)", placeholder="e.g. 1 -3 sqrt(2) -pi") |
|
|
|
|
|
steps_md = gr.Markdown() |
|
|
plot_output = gr.Plot() |
|
|
error_box = gr.Textbox(visible=False) |
|
|
|
|
|
with gr.Row(): |
|
|
solve_button = gr.Button("Plot Polynomial", variant="primary") |
|
|
|
|
|
degree_slider.change(fn=update_template, inputs=degree_slider, outputs=template_display) |
|
|
solve_button.click(fn=solve_polynomial, inputs=[degree_slider, coeff_input], outputs=[steps_md, plot_output, error_box]) |
|
|
|
|
|
demo.load(fn=update_template, inputs=degree_slider, outputs=template_display) |
|
|
|
|
|
demo.launch() |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|