gpt4 book ai didi

python - 如何使用 SymPy 找到给定一阶导数的 n 阶导数?

转载 作者:太空狗 更新时间:2023-10-29 21:02:50 25 4
gpt4 key购买 nike

给定一些 f 和微分方程 x'(t) = f(x (t)),我如何计算 x(n)(t ) x(t)?

例如,给定 f(x(t)) = sin(x( t)),我想获得 x(3)(t) = (cos(x(t))2 − sin(x(t))2) sin(x (t)).

到目前为止我已经尝试过

>>> from sympy import diff, sin
>>> from sympy.abc import x, t
>>> diff(sin(x(t)), t, 2)

这给了我

-sin(x(t))*Derivative(x(t), t)**2 + cos(x(t))*Derivative(x(t), t, t)

但我不确定如何告诉 SymPy Derivative(x(t), t) 是什么,并让它弄清楚 Derivative(x(t), t, t) 等。


回答:

根据下面收到的答案,这是我的最终解决方案:

def diff(x_derivs_known, t, k, simplify=False):
try: n = len(x_derivs_known)
except TypeError: n = None
if n is None:
result = sympy.diff(x_derivs_known, t, k)
if simplify: result = result.simplify()
elif k < n:
result = x_derivs_known[k]
else:
i = n - 1
result = x_derivs_known[i]
while i < k:
result = result.diff(t)
j = len(x_derivs_known)
x0 = None
while j > 1:
j -= 1
result = result.subs(sympy.Derivative(x_derivs_known[0], t, j), x_derivs_known[j])
i += 1
if simplify: result = result.simplify()
return result

例子:

>>> diff((x(t), sympy.sin(x(t))), t, 3, True)
sin(x(t))*cos(2*x(t))

最佳答案

这是一种返回所有导数列表的方法,最多 n

import sympy as sp

x = sp.Function('x')
t = sp.symbols('t')

f = lambda x: x**2 #sp.exp, sp.sin
n = 4 #3, 4, 5

deriv_list = [x(t), f(x(t))] # list of derivatives [x(t), x'(t), x''(t),...]
for i in range(1,n):
df_i = deriv_list[-1].diff(t).replace(sp.Derivative,lambda *args: f(x(t)))
deriv_list.append(df_i)

print(deriv_list)

[x(t), x(t)**2, 2*x(t)**3, 6*x(t)**4, 24*x(t)**5]

使用 f=sp.sin 它返回

 [x(t), sin(x(t)), sin(x(t))*cos(x(t)), -sin(x(t))**3 + sin(x(t))*cos(x(t))**2, -5*sin(x(t))**3*cos(x(t)) + sin(x(t))*cos(x(t))**3]

编辑:计算n次导数的递归函数:

def der_xt(f, n):
if n==1:
return f(x(t))
else:
return der_xt(f,n-1).diff(t).replace(sp.Derivative,lambda *args: f(x(t)))

print(der_xt(sp.sin,3))

-sin(x(t))**3 + sin(x(t))*cos(x(t))**2

关于python - 如何使用 SymPy 找到给定一阶导数的 n 阶导数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40324336/

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