Download app.py from prathamt/quad: direct link, hf CLI and curl.
- Browser
- Download file 2.64 kB
-
https://huggingface.co/spaces/prathamt/quad/resolve/main/app.py
- Command line
-
hf download hf://spaces/prathamt/quad/app.py
-
curl -L -o app.py https://huggingface.co/spaces/prathamt/quad/resolve/main/app.py
2.64 kB
| import gradio as gr | |
| import matplotlib.pyplot as plt | |
| import numpy as np | |
| import cmath | |
| class Quadratic: | |
| """Representing a quadratic expression in the form of ax² + bx + c""" | |
| def __init__(self, a: float, b: float, c: float) -> None: | |
| if all(isinstance(i, (int, float)) for i in (a, b, c)): | |
| if a == 0: | |
| raise ValueError("Coefficient 'a' cannot be 0 for a quadratic equation.") | |
| self.a = a | |
| self.b = b | |
| self.c = c | |
| else: | |
| raise ValueError("Arguments must be int or float") | |
| def __repr__(self) -> str: | |
| return f"{self.a}x² + {self.b}x + {self.c}" | |
| def solveQuad(self): | |
| """Returns roots (real or complex)""" | |
| discriminant = self.b**2 - 4 * self.a * self.c | |
| root1 = (-self.b + cmath.sqrt(discriminant)) / (2 * self.a) | |
| root2 = (-self.b - cmath.sqrt(discriminant)) / (2 * self.a) | |
| return root1, root2 | |
| def evaluate(self, value): | |
| return (self.a * value**2) + (self.b * value) + self.c | |
| def drawFigure(self): | |
| x_axis = np.linspace(-10, 10, 200) | |
| y_axis = self.evaluate(x_axis) | |
| fig, ax = plt.subplots() | |
| ax.plot(x_axis, y_axis) | |
| ax.axhline(0) | |
| ax.axvline(0) | |
| ax.grid(True) | |
| ax.set_title(str(self)) | |
| return fig | |
| # -------- Function for Gradio -------- | |
| def solve_and_plot(a, b, c): | |
| try: | |
| # Convert string inputs to float (supports negative values) | |
| a = float(a) | |
| b = float(b) | |
| c = float(c) | |
| quad = Quadratic(a, b, c) | |
| root1, root2 = quad.solveQuad() | |
| fig = quad.drawFigure() | |
| result = ( | |
| f"Equation: {quad}\n\n" | |
| f"Root 1: {root1}\n" | |
| f"Root 2: {root2}" | |
| ) | |
| return result, fig | |
| except Exception as e: | |
| return f"Error: {str(e)}", None | |
| # -------- Theme with Google Font -------- | |
| theme = gr.themes.Ocean( | |
| font=[ | |
| gr.themes.GoogleFont("Libertinus Math"), | |
| "ui-sans-serif", | |
| "system-ui" | |
| ] | |
| ) | |
| # -------- Gradio UI -------- | |
| interface = gr.Interface( | |
| fn=solve_and_plot, | |
| inputs=[ | |
| gr.Textbox(label="Coefficient a", value="0"), | |
| gr.Textbox(label="Coefficient b", value="0"), | |
| gr.Textbox(label="Coefficient c", value="0"), | |
| ], | |
| outputs=[ | |
| gr.Textbox(label="Solution"), | |
| gr.Plot(label="Graph"), | |
| ], | |
| title="Quadratic Equation Solver", | |
| description="Solve ax² + bx + c = 0 and visualize its graph • Made by Pratham Tripathi", | |
| theme=theme | |
| ) | |
| # -------- Launch -------- | |
| if __name__ == "__main__": | |
| interface.launch() |