在 sympy 中调用 doit 方法后,Subs 对象仍然存在 [英] Subs object still remains after calling doit method in sympy

查看:62
本文介绍了在 sympy 中调用 doit 方法后,Subs 对象仍然存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 sympy 计算一般复合函数导数.在我的具体情况下,脚本如下:

I am trying to calculate general composite function derivative using sympy. In my specific case script is the following:

from sympy import *
t=symbols('t')
p=Function('p')
x=Function('x')
v=diff(x(p(t)),t)
a=diff(v,t)

对于变量 a 它产生:

Derivative(p(t), t)**2*Derivative(x(p(t)), p(t), p(t)) + Derivative(p(t), t, t)*Subs(Derivative(x(_xi_1), _xi_1), (_xi_1,), (p(t),))

如果我调用 doit(),答案仍然包含 subs 对象

If I call doit(), answer still contains subs object

a.doit() #answer: Derivative(p(t), t)**2*Subs(Derivative(x(_xi_3), _xi_3, _xi_3), (_xi_3,), (p(t),)) + Derivative(x(p(t)), p(t))*Derivative(p(t), t, t)

数学上答案是正确的,但我仍然需要以下格式的输出(没有 Subs 对象):

Mathematically the answer is correct but I still need output in following format (without Subs objects):

Derivative(p(t), t)**2*Derivative(x(p(t)), p(t), p(t)) + Derivative(x(p(t)), p(t))*Derivative(p(t), t, t)

有什么办法可以达到预期的效果吗?需要明确的是,与我的原始表达式相比,此示例非常简化,因此我需要通用方法来获得所需的输出.

Is there any way to achieve desired result? To be clear this example is very simplified compared to my original expression so I need general way to get desired output.

推荐答案

确实,在这种情况下重复应用 doit() 会导致两种形式的表达式之间的翻转:一半的时间第一个加数有 Subs,一半时间是第二个.

Indeed, repeated applications of doit() in this case result in flip-flopping between two forms of the expression: half the time the first addend has Subs, half the time it's the second.

但您可以按如下方式处理问题:

But you can deal with the issue as follows:

for b in a.atoms(Subs):
  a = a.xreplace({b: b.doit()})

这将返回 Derivative(p(t), t)**2*Derivative(x(p(t)), p(t), p(t)) + Derivative(x(p(t))), p(t))*Derivative(p(t), t, t) 根据需要.

This returns Derivative(p(t), t)**2*Derivative(x(p(t)), p(t), p(t)) + Derivative(x(p(t)), p(t))*Derivative(p(t), t, t) as desired.

诀窍在于 atoms(Subs) 是表达式中所有 Subs 对象的集合,并且 doit 只应用于它们,而不是应用于只会把事情搞砸的 Derivative 对象.(理想情况下,doit 一开始就不会弄乱派生对象......)

The trick is that atoms(Subs) is the set of all Subs objects in the expression, and doit is applied only to them, not to Derivative objects where it only messes things up. (Ideally, doit would not mess Derivative objects up in the first place...)

这篇关于在 sympy 中调用 doit 方法后,Subs 对象仍然存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆