理解odeint结果 - 与分析解决方案不一致

问题描述 投票:2回答:1

几天前我和odeint一起玩,并认为一些结果很奇怪。所以,我想运行一些非常简单的东西来测试我的代码(如下所示)。

如果(dy / dt)= -x,则积分它应该得到(-x ^ 2)/ 2 + C.我得到的图是完全没有显示出来的。很明显我做错了什么,但我无法弄清楚缺少什么。有人可以给我指点吗?

代码如下 -

import scipy.integrate as scint
import numpy as np
import matplotlib.pyplot as plt

def odefunc(y0, t):
    x = y0
    dxdt = -1*x
    return dxdt

plt.close('all')

t = np.arange(0, 5, 0.02)
y0 = 1

soln = scint.odeint(odefunc, y0, t)

fig1 = plt.figure(1, figsize = (9, 6))
plt.grid(color = 'grey', linestyle = ':', linewidth = 1)
plt.plot(t, soln, marker = 'd', linestyle = 'none', color = 'black')

plt.xlabel('Time')
plt.ylabel('Event')
plt.tight_layout()

这是情节 -

Plot of the solution

我是使用python的新手。这不是一个家庭作业问题或任何事情。我正在学习python而不是任何东西。

python scipy ode
1个回答
2
投票

你写了“如果(dy / dt)= -x,积分它应该得到(-x ^ 2)/ 2 + C”,但我认为你的意思是“If(dy / dt)= -t,积分它应该产生( -t ^ 2)/ 2 + C“。这不是您在Python代码中实现的等式。

你实施的odefunc

def odefunc(y0, t):
    x = y0
    dxdt = -1*x
    return dxdt

对应于微分方程dy / dt = -y。该等式的解是y(t)= y(0)* exp(-t)。这是在图表中绘制的函数。

如果你想用odeint解决dy / dt = -t,那么odefunc应该是

def odefunc(y, t):
    return -t
© www.soinside.com 2019 - 2024. All rights reserved.