Home > Software design >  How do I use multivariable functions in sympy?
How do I use multivariable functions in sympy?

Time:09-17

I was trying to evaluate a multivariable function at a couple of inputs but for some weird reason it's spitting an error


x = Symbol("x")
y = Symbol("y")

f = x*y
f = lambdify(x, y, f)
print(f(3, 3))

If I try to do the same thing with a single variable function instead it'll work as it should but when I try to run this same code with multivariable inputs I get an error like this

TypeError: Argument must be either a string, dict or module but it is: x*y

How do I fix this? I am still very new to SymPy <-<

CodePudding user response:

Function could either be constructed explicitly or as symbol but not as you did. This f = x*y is a mathematical expression see code:

import  sympy as sp

x, y = sp.symbols('x y')

# function
f = sp.symbols('f', cls=sp.Function)
f_eval = f(x, y)
print(f_eval.subs(x, 2))

# expression
expr = sp.Expr(x*y)
print(expr.subs(x, 3))

# lambdify
f = sp.lambdify(args=[x, y], expr=x*y)
print(f(2, 3))

Output

f(2, y)
Expr(3*y)
6

CodePudding user response:

As shown in the docs:

https://docs.sympy.org/latest/modules/utilities/lambdify.html#sympy.utilities.lambdify.lambdify

To call a function like f(x, y) then [x, y] will
be the first argument of the lambdify:

>>> f = lambdify([x, y], x   y)
>>> f(1, 1)
2
  • Related