Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluating a function at a point in SymPy

Tags:

python

sympy

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.

like image 684
Tam Coton Avatar asked Mar 18 '13 13:03

Tam Coton


2 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))
like image 146
Krastanov Avatar answered Oct 29 '22 21:10

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)))
like image 30
askewchan Avatar answered Oct 29 '22 21:10

askewchan