繁体   English   中英

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

[英]How to solve differential equation using Python builtin function odeint?

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

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

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

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

(3×-1)Y '' - (3×+ 2)Y' - (6X-8)Y = 0; y(0)= 2,y'(0)= 3

(注意y中术语的符号)。 对于此等式,您的分析解决方案和y2定义是正确的。

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

第三,你的初始条件是x = 0,但你要整合的x网格从-2开始。 从文档的odeint ,这个参数, t在他们的呼叫签名说明:

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

t:array要求解y的时间点序列。 初始值点应该是此序列的第一个元素。

因此,您必须从0开始积分或提供从-2开始的初始条件。

最后,您的整合范围涵盖了x = 1/3处的奇点。 odeint可能在这里odeint了不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()

在此输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM