简体   繁体   English

使用 sympy 获取 function 的导数作为 function (用于以后的评估和替换)

[英]Getting the derivative of a function as a function with sympy (for later evaluation and substitution)

I want to work with generic functions as long as possible, and only substitute functions at the end.我想尽可能长时间地使用泛型函数,最后只替换函数。 I'd like to define a function as the derivative of another one, define a generic expression with the function and its derivative, and substitute the function at the end.我想将 function 定义为另一个的导数,用 function 及其导数定义一个通用表达式,并在末尾替换 function。 Right now my attempts is as follows, but I get the error 'Derivative' object is not callable :现在我的尝试如下,但我收到错误'Derivative' object is not callable

from sympy import Function
x, y, z = symbols('x y z')
f  = Function('f') 
df = f(x).diff(x)  # <<< I'd like this to be a function of dummy variable x
expr = f(x) * df(z)  + df(y) + df(0) # df is unfortunately not callable
# At the end, substitute with example function
expr.replace(f, Lambda(X, cos(X))) # should return: -cos(x)*sin(z) - sin(y) - sin(0)

I think I got it to work with integrals as follows: I= Lambda( x, integrate( f(y), (y, 0, x))) but that won't work for derivatives.我想我可以按如下方式使用积分: I= Lambda( x, integrate( f(y), (y, 0, x)))但这不适用于导数。 If that helps, I'm fine restricting myself to functions of a single variable for now.如果这有帮助,我现在可以限制自己使用单个变量的函数。

As a bonus, I'd like to get this to work with any combination (products, derivatives, integrals) of the original function.作为奖励,我想让它与原始 function 的任何组合(产品、导数、积分)一起使用。

It's pretty disappointing that f.diff(x) doesn't work, as you say.正如您所说, f.diff(x)不起作用,这非常令人失望。 Maybe someone will create support it sometime in the future.也许有人会在将来的某个时候创建支持它。 In the mean time, there are 2 ways to go about it: either substitute x for your y, z, ... OR lambdify df .同时,有两种方法可以 go 关于它:或者用x代替你的y, z, ...或者 lambdify df

I think the first option will work more consistently in the long run (for example, if you decide to extend to multivariate calculus).我认为从长远来看,第一个选项会更加一致(例如,如果您决定扩展到多元微积分)。 But the expr in second option is far more natural.但是第二个选项中的expr要自然得多。

Using substitution:使用替换:

from sympy import *

x, y, z = symbols('x y z')
X = Symbol('X')

f = Function('f')
df = f(x).diff(x)

expr = f(x) * df.subs(x, z) + df.subs(x, y) + df.subs(x, 0)
print(expr.replace(f, Lambda(X, cos(X))).doit())

Lambdifying df :羔羊化df

from sympy import *

x, y, z = symbols('x y z')
X = Symbol('X')

f = Function('f')
df = lambda t: f(t).diff(t) if isinstance(t, Symbol) else f(X).diff(X).subs(X, t)

expr = f(x) * df(z) + df(y) + df(0)
print(expr.replace(f, Lambda(X, cos(X))).doit())

Both give the desired output.两者都给出了所需的 output。

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

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