Search code examples
pythonsympypython-3.6lambdify

sympy lambdify add two functions


I have two functions created with sympy's lamdify

a = sympy.lambdify((x, y), K / (2 * math.pi) * sympy.cos(theta) / r)
b = sympy.lambdify((x, y), -G / (2 * math.pi) * theta)

How can I create a new function that is the addition of these two functions?

I tried c = a + b but I got

TypeError: unsupported operand type(s) for +: 'function' and 'function'

Solution

  • c = lambda x, y: a(x, y) + b(x,y)
    

    would work. This is not SymPy specific; just combining two Python functions into third.

    But it's more logical to add the expressions before converting to a lambda. For example:

    var('x y')
    expr1 = x + y
    a = lambdify((x, y), expr1)
    expr2 = x/y
    b = lambdify((x, y), expr2)
    c = lambdify((x, y), expr1 + expr2)
    

    Side remark: I would replace math.pi in your function by sympy.pi, because math.pi is just a floating-point number, while sympy.pi is a SymPy object that is recognized as mathematical constant pi.