Evaluating a function at a point in SymPy

Question:

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.

Asked By: Tam Coton

||

Answers:

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))
Answered By: Krastanov

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)))
Answered By: askewchan

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))
Answered By: user3021380
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.