File size: 1,725 Bytes
30ca660
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6cc900
 
 
 
 
 
 
 
 
 
 
 
30ca660
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
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]
    ]
)