File size: 2,941 Bytes
f76a2a8
 
ae5f7c9
 
f76a2a8
ae5f7c9
 
 
 
f76a2a8
ae5f7c9
 
f76a2a8
ae5f7c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16899b5
ae5f7c9
16899b5
 
ae5f7c9
 
f76a2a8
ae5f7c9
f76a2a8
ae5f7c9
 
f76a2a8
 
ae5f7c9
 
f76a2a8
 
ae5f7c9
f76a2a8
ae5f7c9
f76a2a8
ae5f7c9
f76a2a8
ae5f7c9
 
 
f76a2a8
ae5f7c9
 
f76a2a8
 
ae5f7c9
 
f76a2a8
ae5f7c9
f76a2a8
ae5f7c9
 
 
f76a2a8
16899b5
 
 
ae5f7c9
16899b5
ae5f7c9
 
f76a2a8
16899b5
 
ae5f7c9
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
80
import gradio as gr
import numpy as np
import matplotlib.pyplot as plt
import sympy as sp

# Generate abstract polynomial form for given degree
def generate_polynomial_template(degree):
    terms = [f"_x^{degree - i}" for i in range(degree)] + ["_"]
    return " + ".join(terms) + " = 0"

# Solve and plot polynomial
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'))

        # Prepare root output in regular format
        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}"

        # Plotting
        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, ""

# Gradio UI
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()