Search code examples
pythonsympy

Sympy limit raises Value and Syntaxerror


This is my code

from sympy import *
x=symbols('x',positive=True ,real=True)
h=symbols('h', positive=True, real=True)
expr=input('Enter the expression: ')
expr2=expr.replace('x','(x+h)')
actualexp=f"(({expr2})-({expr}))/{h}"
print(limit(actualexp,h,0))

As you see im trying to take a derivative using sympy's limit function, but this raises a Valueerror and a Syntax errorValueError:

Error from parse_expr with transformed code: "((Integer (2 )(Symbol ('x' )+Symbol ('h' )))-(Integer (2 )Symbol ('x' )))/Symbol ('h' )"

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "c:\Users\FAKENAME\Desktop\derivative.py", line 6, in <module>
    actualexp= parse_expr(f"(({expr2})-({expr}))/{h}")
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\FAKENAME\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sympy\parsing\sympy_parser.py", line 1087, in parse_expr
    raise e from ValueError(f"Error from parse_expr with transformed code: {code!r}")
  File "C:\Users\FAKENAME\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sympy\parsing\sympy_parser.py", line 1078, in parse_expr
    rv = eval_expr(code, local_dict, global_dict)
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\FAKENAME\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sympy\parsing\sympy_parser.py", line 906, in eval_expr
    expr = eval(
           ^^^^^
  File "<string>", line 1
    ((Integer (2 )(Symbol ('x' )+Symbol ('h' )))-(Integer (2 )Symbol ('x' )))/Symbol ('h' )
                                                  ^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: invalid syntax. Perhaps you forgot a comma?

i tried googling, no result


Solution

  • You should parse the expression... you are actually passing a string object representing a mathematical expression to limit. You shuold parse the string to make it a true sympy object. Here how to fixed it

    actualexp= parse_expr(f"(({expr2})-({expr}))/{h}")
    
    print(limit(actualexp, h, 0).simplify())
    

    Another example on how to parse expressions