File size: 2,619 Bytes
5543e04
95151f6
5543e04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95151f6
 
 
 
 
 
 
 
 
 
 
 
db31576
 
95151f6
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
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", "+-"]],
)