简体   繁体   English

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

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

I want to solve this differential equations with the given initial conditions: 我想用给定的初始条件求解这个微分方程:

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

the ans should be ans应该是

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

here is my code: 这是我的代码:

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

but what I get is different from the answer. 但我得到的不同于答案。 what have I done wrong? 我做错了什么?

There are several things wrong here. 这里有几个问题。 Firstly, your equation is apparently 首先,你的等式显然是

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

(note the sign of the term in y). (注意y中术语的符号)。 For this equation, your analytical solution and definition of y2 are correct. 对于此等式,您的分析解决方案和y2定义是正确的。

Secondly, as the @Warren Weckesser says, you must pass 2 parameters as y to g : y[0] (y), y[1] (y') and return their derivatives, y' and y''. 其次,正如@Warren Weckesser所说,你必须将2个参数作为y传递给gy[0] (y), y[1] (y')并返回它们的导数y'和y''。

Thirdly, your initial conditions are given for x=0, but your x-grid to integrate on starts at -2. 第三,你的初始条件是x = 0,但你要整合的x网格从-2开始。 From the docs for odeint , this parameter, t in their call signature description: 从文档的odeint ,这个参数, t在他们的呼叫签名说明:

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

t : array A sequence of time points for which to solve for y. t:array要求解y的时间点序列。 The initial value point should be the first element of this sequence. 初始值点应该是此序列的第一个元素。

So you must integrate starting at 0 or provide initial conditions starting at -2. 因此,您必须从0开始积分或提供从-2开始的初始条件。

Finally, your range of integration covers a singularity at x=1/3. 最后,您的整合范围涵盖了x = 1/3处的奇点。 odeint may have a bad time here (but apparently doesn't). odeint可能在这里odeint了不odeint时光(但显然没有)。

Here's one approach that seems to work: 这是一种似乎有效的方法:

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