counting / maths /equations /solve_poly.py
spagestic's picture
feat: enhance Gradio interfaces for cubic, polynomial, quadratic, and simultaneous equation solvers with detailed descriptions and examples
f6cc900
import numpy as np
import gradio as gr
def solve_polynomial(coeffs):
"""
Find roots of a polynomial with given coefficients.
coeffs: list or array-like, highest degree first (e.g., [a, b, c, d, ...])
Returns a numpy array of roots (complex or real).
"""
if not coeffs or all(c == 0 for c in coeffs):
raise ValueError("Coefficient list must not be empty or all zeros.")
return np.roots(coeffs)
def polynomial_solver_interface(coeffs):
"""
Gradio wrapper for solving higher order polynomials.
coeffs: comma-separated string of coefficients, highest degree first.
"""
import numpy as np
try:
coeff_list = [float(c) for c in coeffs.split(",") if c.strip() != ""]
if not coeff_list:
return "Please enter at least one coefficient."
roots = solve_polynomial(coeff_list)
output = f"Polynomial coefficients: {coeff_list}\n\n"
for i, root in enumerate(roots):
if np.isreal(root):
output += f"Root {i+1}: {root.real}\n"
else:
output += f"Root {i+1}: {root}\n"
return output
except Exception as e:
return f"Error: {e}"
poly_solver_interface = gr.Interface(
fn=polynomial_solver_interface,
inputs=gr.Textbox(label="Coefficients (comma-separated, highest degree first)", placeholder="e.g. 1, 0, -2, -8"),
outputs="text",
title="Polynomial Equation Solver",
description="""
Find roots of any polynomial equation. Enter the coefficients separated by commas, starting with the highest degree.
Example: For x⁴ - 2x² - 8 = 0, enter: 1, 0, -2, 0, -8
Supports real and complex roots for polynomials of any degree.
""",
examples=[
["1, 0, -2, 0, -8"],
["2, -3, 0, 1"],
["1, -6, 11, -6"]
]
)