mathwizz / app.py
Aroy1997's picture
Create app.py
ddb99ef verified
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)]
# Plotting
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
# Gradio UI
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()