Sympy:求解具有初始条件误差的微分方程 [英] Sympy: solving differential equation with initial conditions error

查看:107
本文介绍了Sympy:求解具有初始条件误差的微分方程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Sympy 1.2版以来,python Sympy 在给定一些初始条件的情况下,已实现了在简单的微分方程中求解常数的功能.我正在尝试测试此功能,但是不断收到我不知道如何解决的错误.

SinceSympy version 1.2, python Sympy has implemented the ability to solve for the constants in a simple differential equation, given some initial conditions. I was trying to test out this feature, but keep getting an error that I don't know how to solve.

文档表示初始条件的以下格式,我尝试遵循在实现该功能的实际拉取请求中指定的格式.这是代码和错误.

The documentation indicates the following format for initial conditions, and I tried to follow what was specified in the actual pull request that implemented the feature. Here is the code and the error.

import sympy as sp

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

diffeq = sp.Eq(x.diff(t,t) - x, sp.cos(t))
res = sp.dsolve(diffeq, t, ics={x(0): 0, 
                            x.diff(t).subs(t, 0): 0})

错误是:

Traceback (most recent call last):

  File "<ipython-input-20-75c3e1d53138>", line 1, in <module>
    res = sp.dsolve(diffeq, t, ics={x(0): 0, sp.diff(x(t), t).subs(t,0): 0})

TypeError: 'x' object is not callable

推荐答案

我不是sympy的重度用户,但我确实可以使用它-问题是,当您定义 x = sp.Function('x')(t)时,您已经参数 t 传递给它,并且不能再在该行上为其传递 0 res = sp.dsolve(diffeq,t,ics = {x(0):0,sp.diff(x(t),t).subs(t,0):0})-用(t)调用 x 使其成为定义函数".

I am not a heavy user of sympy, but I got that to work - the problem is that when you define x = sp.Function('x')(t) you already got the parameter t to it, and can no longer pass 0 for it at the line res = sp.dsolve(diffeq, t, ics={x(0): 0, sp.diff(x(t), t).subs(t,0): 0}) - The call of x with (t) makes it a "defined function".

因此,将 x 保留为未定义函数,并在创建微分方程时仅在需要的点传递 t 即可:

So, leaving x as an undefined function, and just passing t for it in the points it is needed when creating the differential equation is the way to go:


import sympy as sp

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

diffeq = sp.Eq(x(t).diff(t, t) - x(t), sp.cos(t)) 
res = sp.dsolve(diffeq, ics={x(0): 0, sp.diff(x(t), t).subs(t,0): 0})

(此外,尝试在第二个参数中传递 t 做dsolve会出现另一个错误.

(Also, trying to pass t in the second parameter do dsolve gives another error. The docs tell that sympy should be able to correctly guess it, so I left it out - only to find the correct argument there would be x(t) later)

这给了我res =

Eq(x(t), exp(t)/4 - cos(t)/2 + exp(-t)/4)

这篇关于Sympy:求解具有初始条件误差的微分方程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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