|
|
import numpy as np |
|
|
import matplotlib.pyplot as plt |
|
|
import gradio as gr |
|
|
|
|
|
def plot_polynomial(degree, coeff_input): |
|
|
try: |
|
|
coeffs = list(map(float, coeff_input.strip().split())) |
|
|
if len(coeffs) != degree + 1: |
|
|
return "β οΈ Please enter exactly {} coefficients.".format(degree + 1), None |
|
|
|
|
|
coeffs = np.array(coeffs) |
|
|
roots = np.roots(coeffs) |
|
|
real_roots = [r.real for r in roots if np.isclose(r.imag, 0, atol=1e-5)] |
|
|
|
|
|
|
|
|
x_vals = np.linspace(-10, 10, 400) |
|
|
y_vals = np.polyval(coeffs, x_vals) |
|
|
|
|
|
fig, ax = plt.subplots(figsize=(6, 4)) |
|
|
ax.plot(x_vals, y_vals, label="Polynomial Curve", color="blue") |
|
|
ax.axhline(0, color='black', linewidth=0.5) |
|
|
ax.axvline(0, color='black', linewidth=0.5) |
|
|
|
|
|
for root in real_roots: |
|
|
ax.scatter(root, 0, color="red", s=100) |
|
|
|
|
|
ax.set_title("π Graph of the Polynomial") |
|
|
ax.set_xlabel("x") |
|
|
ax.set_ylabel("f(x)") |
|
|
ax.grid(True, linestyle='--', linewidth=0.5) |
|
|
ax.legend() |
|
|
|
|
|
return "β
Real roots: {}".format(real_roots if real_roots else "None found."), fig |
|
|
except Exception as e: |
|
|
return f"β Error: {e}", None |
|
|
|
|
|
|
|
|
with gr.Blocks() as demo: |
|
|
gr.Markdown("## π Welcome to MathWizz π\nPlot and Analyze Your Polynomial") |
|
|
|
|
|
degree = gr.Slider(label="Select Degree", minimum=1, maximum=10, value=2, step=1) |
|
|
coeff_input = gr.Textbox(label="Enter Coefficients (space-separated)", placeholder="e.g. 1 -3 2") |
|
|
|
|
|
output_text = gr.Textbox(label="Result") |
|
|
output_plot = gr.Plot(label="Polynomial Curve") |
|
|
|
|
|
submit = gr.Button("Plot Polynomial") |
|
|
|
|
|
submit.click(fn=plot_polynomial, |
|
|
inputs=[degree, coeff_input], |
|
|
outputs=[output_text, output_plot]) |
|
|
|
|
|
demo.launch() |
|
|
|