python - 如何使用 Python 内置函数 odeint 求解微分方程?

标签 python numpy scipy differential-equations odeint

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

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

答案应该是

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()

但是我得到的和答案不一样。 我做错了什么?

最佳答案

这里有几处错误。首先,你的等式显然是

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

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

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

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

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

t : array A sequence of time points for which to solve for y. The initial value point should be the first element of this sequence.

因此您必须从 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()

enter image description here

关于python - 如何使用 Python 内置函数 odeint 求解微分方程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27820725/

相关文章:

python - numpy/scipy 中的快速二维刚体变换

Python Selenium 按名称查找元素

python - 为什么 `int in List[List[int]]` 返回 `False` 但 `np.int in List[List[int]]` 返回 `True` ?

python-3.x - 有 numpy.there 吗?

python - 如何将数组中的每个元素与大数相乘而不会出现 OverflowError : Python int too large to convert to C long?

python - 使用数组的 Numpy 索引

python - 如何使用花式索引创建 Numpy 数组

Python/PostgreSQL - 如何使用 psycopg2 库将一个表复制到另一个表?

python - 向 django 查询添加虚拟字段

python - 如何在 python - networkx 包中根据边缘的密度和权重找到网络簇