Reputation: 864
I'm trying to code various optimisation methods, as a way of revising. I want to be able to use SymPy to evaluate a function with an arbitrary number of variables at a given point, where the co-ordinates of the point are stored in an array.
For example, I'd like to evaluate f(x,y) = 3*x**2 - 2*x*y + y**2 + 4*x + 3*y
at the point b = [1,2]
. But I'd really like a general way of doing it, that can handle a function with any number of variables and an appropriate length array as the point to be evaluated as, so sympy.evalf(f, subs = {foo})
isn't really very useful.
Upvotes: 11
Views: 14498
Reputation: 166
lambdify
is a good option to generate a Python-callable function.
An example, assuming you have a function f
and the symbols x
and y
:
from sympy import lambdify
import numpy as np
callable_fct = lambdify((x, y), f)
xn = np.arange(0, 2, 0.1)
yn = 3
print(callable_fct(xn, yn))
Upvotes: 1
Reputation: 46530
I would also expect this to be easier to do, but here's a good workaround:
If you know the symbol names ('x'
,'y'
, e.g.), you can create a dict
on the fly using zip
:
fvars = sympy.symbols('x, y') #these probably already exist, use: fvars = [x,y]
b = [1,2]
sympy.evalf(f, subs = dict(zip(fvars,b)))
Upvotes: 1
Reputation: 6549
You are working with SymPy expression trees, not functions. On any expression you can do:
>>> vars = sorted(expression.free_symbols)
>>> evaluated = expression.subs(*zip(vars, your_values))
Upvotes: 4