python转换函数使用,使用SymPy将符号表达式转换为Python函数

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]

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.

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]

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)

解决方案

You want lambdify.

f = lambdify(((x, y, z),), lagrange_eqs(a))

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.

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.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值