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.
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))
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)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With