counting / maths /equations /solve_simultaneous.py
spagestic's picture
feat: enhance Gradio interfaces for cubic, polynomial, quadratic, and simultaneous equation solvers with detailed descriptions and examples
f6cc900
Raw History Blame Contribute Delete
1.86 kB
import gradio as gr
import numpy as np
def solve_simultaneous_interface(coeffs, constants):
"""
coeffs: Multiline string, each line is comma-separated coefficients for one equation.
constants: Comma-separated string of constants (right-hand side values).
"""
try:
coeff_lines = [line.strip() for line in coeffs.strip().splitlines() if line.strip()]
matrix = [list(map(float, line.split(','))) for line in coeff_lines]
A = np.array(matrix)
b = np.array([float(x) for x in constants.strip().split(',')])
if A.shape[0] != A.shape[1]:
return f"Number of equations and unknowns must match (got {A.shape[0]} equations, {A.shape[1]} unknowns)."
if b.shape[0] != A.shape[0]:
return f"Number of constants must match number of equations."
solution = np.linalg.solve(A, b)
output = ""
for idx, val in enumerate(solution):
output += f"Variable {idx+1}: {val}\n"
return output
except Exception as e:
return f"Error: {e}"
simultaneous_solver_interface = gr.Interface(
fn=solve_simultaneous_interface,
inputs=[
gr.Textbox(lines=4, label="Coefficients (one equation per line, comma-separated)", placeholder="e.g.\n1,2\n3,4"),
gr.Textbox(label="Constants (comma-separated)", placeholder="e.g. 5, 6")
],
outputs="text",
title="Simultaneous Linear Equation Solver",
description="""
Solve systems of simultaneous linear equations. Enter the coefficients for each equation (one per line, comma-separated) and the constants (right-hand side values).\n\nExample: For the system\n\n x + 2y = 5\n 3x + 4y = 6\n\nEnter coefficients:\n1,2\n3,4\n\nEnter constants:\n5,6
""",
examples=[
["1,2\n3,4", "5,6"],
["2,1\n1,3", "8,13"],
["1,1,1\n2,3,4\n1,2,3", "6,20,14"]
]
)