使用SymPy将符号表达式转换为Python函数 [英] Convert symbolic expressions to Python functions using SymPy
问题描述
我有一个相当大的符号函数,该函数针对循环中参数的不同值进行求值.在每次迭代中,在找到函数的表达式之后,将导出偏导数.像这样:
I have a rather large symbolic function that is evaluated for different values of a parameter in a loop. In each iteration, after finding the expression of the function, partial derivatives are derived. Something like this:
from sympy import diff, symbols,exp
def lagrange_eqs(a):
x,y,z= symbols('x y z')
FUNC=x**2-2*x*y**2+z+a*exp(z)
d_lgrng_1=diff(FUNC,x)
d_lgrng_2=diff(FUNC,y)
d_lgrng_3=diff(FUNC,z)
return [d_lgrng_1,d_lgrng_2,d_lgrng_3]
接下来,我需要将此函数的输出转换为Python函数,以便可以使用fsolve
查找导数为零的x,y,z值.该函数必须以x,y,z作为列表.
Next, I need to convert the output of this function to a Python function so that I can use fsolve
to find x, y, z values for which derivatives are zero. The function must take x,y,z as a list.
现在这是我的问题:如何将上述函数的输出转换为Python函数,然后可以将其传递给求解器.这样的函数应如下所示(对于a = 3):
Now here is my problem: how do I convert the output of the above function to a Python function which could be passed on to a solver. Such a function should look like this (for a=3):
def lagrange_eqs_solve(X):
x,y,z=X
return [2*x - 2*y**2, -4*x*y, 3*exp(z) + 1]
我只是复制了第一个函数的输出以构建第二个函数.有什么办法可以编码吗? (Matlab为此具有一个内置函数,称为matlabFunction)
I simply copied the output of the first function to build the second one. Is there a way I could code it? (Matlab has a built-in function for this, called matlabFunction)
推荐答案
您要 lambdify
.
f = lambdify(((x, y, z),), lagrange_eqs(a))
将为您提供Python函数f
,您可以像f((1, 2, 3))
那样对其进行评估(对于x=1
,y=2
,z=3
).我已经在元组中进行了论证,以便可以与scipy的fsolve
一起使用.
will give you a Python function f
that you can evaluate like f((1, 2, 3))
(for x=1
, y=2
, z=3
). I have made the arguments in a tuple so that it will work with scipy's fsolve
.
您可以将modules
标志设置为lambdify,以确定exp
函数的来源.例如,要使用numpy
,请使用lambdify((x, y, z), lagrange_eqs(a), modules="numpy")
.要使用标准库数学库,请使用modules="math"
.默认情况下,如果已安装,则使用numpy,否则使用math.
You can set the modules
flag to lambdify to determine where the exp
function will come from. For instance, to use numpy
, use lambdify((x, y, z), lagrange_eqs(a), modules="numpy")
. To use the standard library math library, use modules="math"
. By default, numpy is used if it is installed, otherwise math is used.
这篇关于使用SymPy将符号表达式转换为Python函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!