gpt4 book ai didi

python - 在表达式树中查找和替换函数

转载 作者:太空宇宙 更新时间:2023-11-03 15:36:31 25 4
gpt4 key购买 nike

我需要在 SymPy 表达式树中找到所有用户创建的函数(以及用户函数的导数之类的东西),然后用标准的用户定义符号替换该位置

from sympy import *
t=symbols('t')

现在创建用户制作的 SymPy 函数:

theta_t = Function(r'\theta')(t)

此外,我还创建了要替换 theta_t 的符号:

theta = Symbol(r'\theta')

我想要使用的表达式是:

y = sin(theta_t)

这是它相对于t的导数:

dydt = y.diff(t)

我想查找并替换 d/dt(theta(t))theta_t 为符号 omegatheta。例如,替换后我希望 dydt 为:

dydt_new = cos(theta)*omega

现在我可以用数字方式处理最后一个表达式,例如使用 lambdify

最佳答案

您可以像其他任何东西一样替换衍生品。您只需小心在实际函数之前替换导数即可。以下对我有用:

from sympy import *

t = symbols('t')
theta_t = Function('theta')(t)
theta = Symbol('theta')
omega = Symbol('omega')
y = sin(theta_t)
dydt = y.diff(t)

dydt_new = dydt.subs([
( diff(theta_t,t), omega ),
( theta_t, theta ),
])

assert dydt_new==cos(theta)*omega

请注意,如果交换替换顺序,此操作会失败。

关于python - 在表达式树中查找和替换函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42473761/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com