Download agent/tools/math_solver.py from AlexTrinityBlock/Final_Assignment_Template: direct link, hf CLI and curl.
- Browser
- Download file 1.75 kB
-
https://huggingface.co/spaces/AlexTrinityBlock/Final_Assignment_Template/resolve/40deb663d0db6a7c0774ccdfd23aea9e4dbc08f2/agent/tools/math_solver.py
- Command line
-
hf download hf://spaces/AlexTrinityBlock/Final_Assignment_Template@40deb663d0db6a7c0774ccdfd23aea9e4dbc08f2/agent/tools/math_solver.py
-
curl -L -o math_solver.py https://huggingface.co/spaces/AlexTrinityBlock/Final_Assignment_Template/resolve/40deb663d0db6a7c0774ccdfd23aea9e4dbc08f2/agent/tools/math_solver.py
1.75 kB
| from colorama import Fore, Style # type: ignore[import] | |
| from langchain_core.tools import tool | |
| from sympy import sympify, N # type: ignore[import] | |
| def math_solver(expression: str) -> str: | |
| """ | |
| Evaluate a mathematical expression using SymPy symbolic computation. | |
| This tool converts a string expression into a SymPy symbolic object and | |
| evaluates it with arbitrary precision. Unlike standard floating-point | |
| arithmetic, SymPy uses exact rational and symbolic representations | |
| internally, so results are free from floating-point rounding errors. | |
| Supported syntax includes: | |
| - Basic arithmetic: +, -, *, /, ** (power) | |
| - Fractions: "1/3 + 2/7" (exact rational arithmetic) | |
| - Square roots: "sqrt(2)", "sqrt(3)/2" | |
| - Trigonometric functions: "sin(pi/4)", "cos(pi/3)", "tan(pi/6)" | |
| - Logarithms: "log(100)", "ln(e**2)" | |
| - Constants: "pi", "E" (Euler's number) | |
| - Factorials: "factorial(10)" | |
| - Combinations: "binomial(10, 3)" | |
| - Complex expressions: "1/3 + 2/7 * sqrt(2)" | |
| Args: | |
| expression: A mathematical expression string to evaluate. | |
| Example: "1/3 + 2/7 * sqrt(2)" | |
| Returns: | |
| A string containing both the exact symbolic result and a numerical | |
| approximation to 10 decimal places. | |
| """ | |
| try: | |
| expr = sympify(expression) | |
| exact = str(expr) | |
| numeric = str(N(expr, 10)) | |
| print(f"{Fore.MAGENTA}[MathSolver] {expression}{Style.RESET_ALL} = {numeric}") | |
| return f"Exact: {exact}\nNumeric (10 digits): {numeric}" | |
| except Exception as e: | |
| return f"Error evaluating expression: {e}" | |
| if __name__ == "__main__": | |
| result = math_solver.invoke({"expression": "1/3 + 2/7 * sqrt(2)"}) | |
| print(result) | |