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'
, eg), 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)))
lambdify
is a good option to generate a Python-callable function, and you can then use numpy arrays. As an example, assuming you have your function f
and the symbols x
and y
:
f2 = lambdify((x, y), f)
import numpy as np
xn = np.arage(0, 2, 0.1)
yn = 3
print(f2(xn, yn))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.