Search code examples
pythonsympysymbolic-math

Parsing a symbolic expression that includes user-defined functions in SymPy


I have some equations that call other functions. I want to write this symbolically, is it possible to do this in Sympy?

Here's an simplified example of what I'm trying to do:

x = sp.Symbol('x')
omega = sp.Function('omega')(x ** 2)

eq_1 = sp.sympify("omega(x)")

eq_1 is calling function omega with argument x , returning x**2. Any ideas on how I can implement this?


Solution

  • x = sp.Symbol('x')
    omega = sp.Lambda(x, x**2)
    eq_1 = sp.sympify("omega(x)", locals={"omega": omega})
    

    The key points:

    • Lambda is a way to create a SymPy function which performs a specific operation
    • locals is a parameter of sympify which links substrings of the input, such as "omega", to the SymPy objects you created. Without it, sympify will only link built-in functions like exp or sin, but it will not be guessing whether "omega" in the input really means your function, or an unrelated letter omega.