简体   繁体   English

在 SymPy 中的某个点评估 function

[英]Evaluating a function at a point in 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.我希望能够使用 SymPy 来评估 function 在给定点具有任意数量的变量,其中点的坐标存储在数组中。

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] .例如,我想评估f(x,y) = 3*x**2 - 2*x*y + y**2 + 4*x + 3*yb = [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.但我真的很喜欢一种通用的方法,它可以处理带有任意数量变量和适当长度数组的 function 作为要评估的点,所以sympy.evalf(f, subs = {foo})是'真的不是很有用。

You are working with SymPy expression trees, not functions. 您正在使用SymPy表达式树,而不是函数。 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 : 如果您知道符号名称(例如'x''y' ),则可以使用zip即时创建dict

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. lambdify是生成 Python 可调用 function 的好选择,然后您可以使用 numpy arrays。 As an example, assuming you have your function f and the symbols x and y :例如,假设您有 function f和符号xy

f2 = lambdify((x, y), f)
import numpy as np
xn = np.arage(0, 2, 0.1)
yn = 3
print(f2(xn, yn))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM