|
|
import gradio as gr |
|
|
import numpy as np |
|
|
import matplotlib.pyplot as plt |
|
|
import sympy as sp |
|
|
|
|
|
|
|
|
def generate_polynomial_template(degree): |
|
|
terms = [f"_x^{degree - i}" for i in range(degree)] + ["_"] |
|
|
return " + ".join(terms) + " = 0" |
|
|
|
|
|
|
|
|
def solve_polynomial(degree, coeff_string): |
|
|
try: |
|
|
coeffs = list(map(float, coeff_string.strip().split())) |
|
|
if len(coeffs) != degree + 1: |
|
|
return "โ ๏ธ Please enter exactly {} coefficients.".format(degree + 1), None, None |
|
|
|
|
|
poly = sum([coeffs[i] * sp.symbols('x')**(degree - i) for i in range(degree + 1)]) |
|
|
simplified = sp.simplify(poly) |
|
|
factored = sp.factor(simplified) |
|
|
roots = sp.solve(sp.Eq(simplified, 0), sp.symbols('x')) |
|
|
|
|
|
|
|
|
roots_output = "$$" |
|
|
for i, r in enumerate(roots, 1): |
|
|
roots_output += f"r_{{{i}}} = {sp.latex(sp.nsimplify(r, rational=True))} \\ " |
|
|
roots_output += "$$" |
|
|
|
|
|
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" |
|
|
steps_output += f"### ๐คฉ Factored\n\n$$ {sp.latex(factored)} = 0 $$\n\n" |
|
|
steps_output += f"### ๐ฅฎ Roots (Real and Complex)\n\n{roots_output}" |
|
|
|
|
|
|
|
|
x_vals = np.linspace(-10, 10, 400) |
|
|
y_vals = np.polyval(coeffs, x_vals) |
|
|
|
|
|
fig, ax = plt.subplots() |
|
|
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)") |
|
|
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 (Symbolic + 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)", placeholder="e.g. 1 -6 11 -6") |
|
|
|
|
|
steps_md = gr.Markdown() |
|
|
plot_output = gr.Plot() |
|
|
error_box = gr.Textbox(visible=False) |
|
|
|
|
|
with gr.Row(): |
|
|
solve_button = gr.Button("Plot Polynomial") |
|
|
|
|
|
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() |
|
|
|
|
|
|
|
|
|