gpt4 book ai didi

python - 无法区分 Sympy 中的复杂变量

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

(我知道标题听起来像是 Sympy Can't differentiate wrt the variable 的重复问题,但我相当确定它完全不同。如果我弄错了,我提前道歉)

我正在尝试使用哈密顿力学求解双摆,但 Sympy 在获取其中一个导数时遇到困难。代码如下,但阅读 iPython Notebook over at nbviewer.ipython.org 更容易

from __future__ import division
from sympy import *
init_session()
r_1,r_2,l_1,l_2, m_1, m_2, rdot_1, rdot_2,g = symbols("r_1 r_2 l_1 l_2 m_1 m_2 \dot{r_1} \dot{r_2} g")
phi_1, phi_2 = symbols("phi_1 phi_2", cls=Function)
phi_1 = phi_1(t)
phi_2 = phi_2(t)

r_1 = Matrix([l_1 * sin(phi_1), -l_1 * cos(phi_1)])
rdot_1 = r_1.diff(t)
r_2 = Matrix([r_1[0] + l_2 * sin(phi_2), r_1[1] -l_2 * cos(phi_2)])
rdot_2 = r_2.diff(t)

T = (1/2) * m_1 * rdot_1.T * rdot_1 + (1/2) * m_2 * rdot_2.T * rdot_2
T = T[0]

U = -g * ((m_1 * r_1[1]) + (m_2 * r_2[1]))

L = symbols("\mathcal{L}")
L = T - U

H = symbols("\mathcal{H}")
H = T + U

p_1, p_2 = symbols("p_1 p_2")
p_1 = L.diff(phi_1.diff(t))
p_2 = L.diff(phi_2.diff(t))

eq1_1 = p_1.diff(t) + H.diff(phi_1)
eq1_2 = p_2.diff(t) + H.diff(phi_2)
eq2_1 = phi_1.diff(t) - H.diff(p_1)

最后一行产生以下错误:

ValueError                                Traceback (most recent call last)
<ipython-input-96-83bfafadd08f> in <module>()
----> 1 eq2_1 = phi_1.diff(t) - H.diff(p_1)
2 eq2_2 = phi_2.diff(t) - H.diff(p_2)

/Library/Python/2.7/site-packages/sympy/core/expr.pyc in diff(self, *symbols, **assumptions)
2773 new_symbols = list(map(sympify, symbols)) # e.g. x, 2, y, z
2774 assumptions.setdefault("evaluate", True)
-> 2775 return Derivative(self, *new_symbols, **assumptions)
2776
2777 ###########################################################################

/Library/Python/2.7/site-packages/sympy/core/function.pyc in __new__(cls, expr, *variables, **assumptions)
1027 from sympy.utilities.misc import filldedent
1028 raise ValueError(filldedent('''
-> 1029 Can\'t differentiate wrt the variable: %s, %s''' % (v, count)))
1030
1031 if all_zero and not count == 0:
ValueError:
Can't differentiate wrt the variable:
1.0*l_1*(l_1*m_1*Derivative(phi_1(t), t) +
l_1*m_2*Derivative(phi_1(t), t) + l_2*m_2*cos(phi_1(t) -
phi_2(t))*Derivative(phi_2(t), t)), 1

是不是表达式太复杂了?或者我误解了如何使用 diff() ?

最佳答案

本质上是同样的问题。 diff 的第二个参数(或者作为方法调用时的唯一参数)应该是单个符号,而不是表达式。在这种情况下,您的微分“变量”是一个完整的表达式,这在数学上甚至没有意义。

关于python - 无法区分 Sympy 中的复杂变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25188084/

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