Sympy:求解微分方程

Sympy: solve a differential equation

我想找到一种求解以下微分方程的优雅方法:

from sympy import *
init_printing()

M, phi, t, r = symbols('M phi t r')

eq = Eq(-M * phi(t).diff(t), Rational(3, 2) * m * r**2 * phi(t).diff(t) * phi(t).diff(t,t))

我假设 phi(t).diff(t) 不为零。因此,左侧和右侧被缩短了。

我是这样找到解决方案的:

# I assume d/dt(phi(t)) != 0

theta = symbols('theta')
eq = eq.subs({phi(t).diff(t, 2): theta})  # remove the second derivative
eq = eq.subs({phi(t).diff(t): 1})  # the first derivative is shortened
eq = eq.subs({theta: phi(t).diff(t, 2)})  # get the second derivative back

dsolve(eq, phi(t))

如何更优雅地解决这个问题?

理想情况下 dsolve() 能够直接求解方程,但它不知道如何(它需要学习它可以对方程进行因式分解并独立求解因式)。我为它开了一个issue

我唯一的其他建议是直接将 phi' 分开:

eq = Eq(eq.lhs/phi(t).diff(t), eq.rhs/phi(t).diff(t))

您也可以使用

eq.xreplace({phi(t).diff(t): 1})

在不修改二阶导数的情况下用 1 替换一阶导数(与 subs 不同,xreplace 没有关于它替换什么的数学知识;它只是准确地替换表达式)。

别忘了 phi(t) = C1 也是一个解(当 phi' 等于 0 时)。