Point-to-point function evaluation in SymPy

I am trying to code various optimization 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 coordinates of the point are stored in an array.

For example, I would like to estimate f(x,y) = 3*x**2 - 2*x*y + y**2 + 4*x + 3*y at the point b = [1,2] . But I would really like the general way to do this, which can handle a function with any number of variables and an appropriate length array as the point to be evaluated, so sympy.evalf(f, subs = {foo}) is actually not very useful.

+8
python sympy
source share
2 answers

You are working with SymPy expression trees, not functions. In any expression, you can:

 >>> vars = sorted(expression.free_symbols) >>> evaluated = expression.subs(*zip(vars, your_values)) 
+4
source share

I would also expect this to be easier to do, but here's a good way:

If you know the character names ( 'x' , 'y' , for example), 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))) 
+1
source share

All Articles