Spaces:
Runtime error
Runtime error
import gradio as gr | |
import numpy as np | |
def solve_cubic(a, b, c, d): | |
""" | |
Solve cubic equation: a*x^3 + b*x^2 + c*x + d = 0 | |
Returns a tuple of three roots (complex or real). | |
""" | |
if a == 0: | |
# Degenerates to quadratic | |
from .solve_quadratic import solve_quadratic | |
result = solve_quadratic(b, c, d, return_format="dict") | |
roots = result["roots"] | |
return (roots[0], roots[1], None) | |
# Use numpy.roots for cubic | |
roots = np.roots([a, b, c, d]) | |
# Ensure three roots (may be complex) | |
if len(roots) < 3: | |
roots = tuple(list(roots) + [None]*(3-len(roots))) | |
else: | |
roots = tuple(roots) | |
return roots | |
def cubic_solver_wrapper(a, b, c, d): | |
roots = solve_cubic(a, b, c, d) | |
output = f"Equation: {a}x³ + {b}x² + {c}x + {d} = 0\n\n" | |
for i, root in enumerate(roots): | |
if root is not None: | |
if np.isreal(root): | |
output += f"Root {i+1}: {root.real}\n" | |
else: | |
output += f"Root {i+1}: {root}\n" | |
return output | |
cubic_solver_interface = gr.Interface( | |
fn=cubic_solver_wrapper, | |
inputs=[ | |
gr.Number(label="a (coefficient of x³)"), | |
gr.Number(label="b (coefficient of x²)"), | |
gr.Number(label="c (coefficient of x)"), | |
gr.Number(label="d (constant)") | |
], | |
outputs="text", | |
title="Cubic Equation Solver", | |
description=""" | |
Solve cubic equations of the form ax³ + bx² + cx + d = 0. Enter the coefficients for your cubic equation. | |
Example: For x³ - 6x² + 11x - 6 = 0, enter a=1, b=-6, c=11, d=-6. | |
Returns all real and complex roots. | |
""", | |
examples=[ | |
[1, -6, 11, -6], | |
[2, 0, -4, 2], | |
[1, 0, 0, -8] | |
] | |
) | |