Spaces:
Runtime error
Runtime error
import sympy | |
import gradio as gr | |
def calculate_limit(expression_str: str, variable_str: str, point_str: str, direction: str = '+-') -> str: | |
""" | |
Calculates the limit of an expression as a variable approaches a point. | |
Args: | |
expression_str: The mathematical expression as a string (e.g., "sin(x)/x"). | |
variable_str: The variable in the expression (e.g., "x"). | |
point_str: The point the variable is approaching (e.g., "0", "oo" for infinity). | |
direction: The direction of the limit ('+', '-', or '+-' for both sides). | |
Returns: | |
A string representing the limit or an error message. | |
""" | |
try: | |
var = sympy.Symbol(variable_str) | |
local_dict = {variable_str: var} | |
expr = sympy.parse_expr(expression_str, local_dict=local_dict, transformations='all') | |
if point_str.lower() == 'oo': | |
point = sympy.oo | |
elif point_str.lower() == '-oo': | |
point = -sympy.oo | |
else: | |
point = sympy.sympify(point_str) | |
if direction == '+': | |
limit_val = sympy.limit(expr, var, point, dir='+') | |
elif direction == '-': | |
limit_val = sympy.limit(expr, var, point, dir='-') | |
else: | |
limit_val = sympy.limit(expr, var, point) | |
return str(limit_val) | |
except (sympy.SympifyError, TypeError, SyntaxError) as e: | |
return f"Error parsing expression or point: {e}. Ensure valid Sympy syntax (e.g. use 'oo' for infinity, ensure variables match)." | |
except Exception as e: | |
return f"An unexpected error occurred: {e}" | |
limit_interface = gr.Interface( | |
fn=calculate_limit, | |
inputs=[ | |
gr.Textbox(label="Expression (e.g., sin(x)/x, x**2, exp(-x))", value="sin(x)/x"), | |
gr.Textbox(label="Variable (e.g., x)", value="x"), | |
gr.Textbox(label="Point (e.g., 0, 1, oo, -oo, pi)", value="0"), | |
gr.Radio(choices=["+-", "+", "-"], label="Direction", value="+-") | |
], | |
outputs="text", | |
title="Limit Calculator", | |
description="Calculate the limit of an expression.\n\n**Description:**\nThis tool calculates the limit of a mathematical expression as a variable approaches a point. Use 'oo' for infinity. Ensure the variable in the expression matches the variable input.\n\n**Examples:**\n- Expression: sin(x)/x, Variable: x, Point: 0, Direction: '+-' → Output: 1\n- Expression: 1/x, Variable: x, Point: 0, Direction: '+' → Output: oo\n- Expression: exp(-x), Variable: x, Point: oo, Direction: '+-' → Output: 0", | |
examples=[["sin(x)/x", "x", "0", "+-"], ["1/x", "x", "0", "+"], ["exp(-x)", "x", "oo", "+-"]], | |
) | |