【问题标题】:How to solve differential equation using Python builtin function odeint?如何使用 Python 内置函数 odeint 求解微分方程?
【发布时间】:2015-03-05 10:08:25
【问题描述】:

我想用给定的初始条件求解这个微分方程:

(3x-1)y''-(3x+2)y'+(6x-8)y=0, y(0)=2, y'(0)=3

ans 应该是

y=2*exp(2*x)-x*exp(-x)

这是我的代码:

def g(y,x):
    y0 = y[0]
    y1 = y[1]
    y2 = (6*x-8)*y0/(3*x-1)+(3*x+2)*y1/(3*x-1)
    return [y1,y2]

init = [2.0, 3.0]
x=np.linspace(-2,2,100)
sol=spi.odeint(g,init,x)
plt.plot(x,sol[:,0])
plt.show()

但我得到的与答案不同。 我做错了什么?

【问题讨论】:

    标签: python numpy scipy differential-equations odeint


    【解决方案1】:

    这里有几个问题。首先,你的方程显然是

    (3x-1)y''-(3x+2)y'-(6x-8)y=0; y(0)=2, y'(0)=3

    (注意 y 中项的符号)。对于这个方程,y2 的解析解和定义是正确的。

    其次,正如@Warren Weckesser 所说,您必须将两个参数作为y 传递给gy[0] (y)、y[1] (y') 并返回它们的导数 y' 和 y' '。

    第三,您的初始条件为 x=0,但您要积分的 x 网格从 -2 开始。来自odeint 的文档,此参数t 在其调用签名描述中:

    odeint(func, y0, t, args=(),...):

    t : 数组 求解 y 的时间点序列。最初的 值点应该是这个序列的第一个元素。

    所以你必须从 0 开始积分或提供从 -2 开始的初始条件。

    最后,您的积分范围涵盖了 x=1/3 处的奇点。 odeint 可能在这里过得不好(但显然没有)。

    这是一种似乎可行的方法:

    import numpy as np
    import scipy as sp
    from scipy.integrate import odeint
    import matplotlib.pyplot as plt
    
    def g(y, x):
        y0 = y[0]
        y1 = y[1]
        y2 = ((3*x+2)*y1 + (6*x-8)*y0)/(3*x-1)
        return y1, y2
    
    # Initial conditions on y, y' at x=0
    init = 2.0, 3.0
    # First integrate from 0 to 2
    x = np.linspace(0,2,100)
    sol=odeint(g, init, x)
    # Then integrate from 0 to -2
    plt.plot(x, sol[:,0], color='b')
    x = np.linspace(0,-2,100)
    sol=odeint(g, init, x)
    plt.plot(x, sol[:,0], color='b')
    
    # The analytical answer in red dots
    exact_x = np.linspace(-2,2,10)
    exact_y = 2*np.exp(2*exact_x)-exact_x*np.exp(-exact_x)
    plt.plot(exact_x,exact_y, 'o', color='r', label='exact')
    plt.legend()
    
    plt.show()
    

    【讨论】:

    • 对于二阶微分方程,init 的长度应为 2,而不是 3(g 应返回长度为 2 的数组)。
    • 你说得对:我很困惑。我已经编辑以更正它。
    猜你喜欢
    • 1970-01-01
    • 2017-10-06
    • 2018-02-08
    • 2012-02-28
    • 2015-12-13
    • 1970-01-01
    • 1970-01-01
    • 2017-11-18
    • 1970-01-01
    相关资源
    最近更新 更多