【问题标题】:Understanding odeint results - disagreement with analytical solution了解 odeint 结果 - 与分析解决方案不一致
【发布时间】:2019-02-16 13:40:56
【问题描述】:

几天前我在玩 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】:

    您写了“如果 (dy/dt) = -x,积分它应该产生 (-x^2)/2 + C”,但我认为您的意思是“如果 (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
    

    【讨论】:

    • “我认为你的意思是“如果 (dy/dt) = -t,整合它应该产生 (-t^2)/2 + C”。 - 这就是我想说的。你的回答很有意义!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-07
    • 2021-11-20
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 2021-10-28
    相关资源
    最近更新 更多