在Python中使用odeint实现积分数学方程 [英] implement an integration math equation using odeint in Python
问题描述
我正在尝试使用scipy.odeint函数在python中求解以下方程式.
I am trying to solve the following equation in python using the scipy.odeint function.
目前,我能够实现这种形式的方程式
Currently I am able to implement this form of the equation
在python中使用以下脚本:
in python using the following script:
def dY(y1, x):
a = 0.001
yin = 1
C = 0.01
N = 1
dC = C/N
b1 = 0
return (a/dC)*(yin-y1)+b1*dC
x = np.linspace(0,20,1000)
y0 = 0
res = odeint(dY, y0, x)
plt.plot(t,res, '-')
plt.show()
我的第一个方程式的问题是"i".我不知道如何对方程进行积分,但仍然能够提供当前和以前的"y"(yi-1和yi)值. "i"只是一个在0..100范围内的序列号.
My problem with the first equation is 'i'. I don't know how to integrate the equation and still be able to provide the current and previous 'y'(yi-1 and yi) values. 'i' is simply a sequence number that is within a range of 0..100.
原始等式为:
我用y,x,a,b和C重写了
Which I rewrote using y,x,a,b and C
Edit2: 我编辑了Pierre de Buyl的代码,并更改了N值.幸运的是,我有一个验证表来验证结果.不幸的是,结果并不相等.
I edited Pierre de Buyl' code and changed the N value. Luckily I have a validation table to validate the outcome against. Unfortunately, the results are not equal.
这是我的验证表:
这是numpy的输出:
and here is the numpy output:
使用的代码:
def dY(y, x):
a = 0.001
yin = 1
C = 0.01
N = 3
dC = C/N
b1 = 0.01
y_diff = -np.copy(y)
y_diff[0] += yin
y_diff[1:] += y[:-1]
return (a/dC)*(y_diff)+b1*dC
x = np.linspace(0,20,11)
y0 = np.zeros(3)
res = odeint(dY, y0, x)
plt.plot(x,res, '-')
如您所见,值相差0.02 ..
as you can see the values are different by an offset of 0.02..
我错过了导致偏移量的东西吗?
Am I missing something that results in this offset?
推荐答案
The equation is a "coupled" ordinary differential equation (see "System of ODEs" on Wikipedia.
变量是一个包含y[0]
,y[1]
等的向量.要求解ODE,必须将向量作为初始条件,函数dY
也必须返回向量.
The variable is a vector containing y[0]
, y[1]
, etc. To solve the ODE you must feed a vector as the initial condition and the function dY
must return a vector as well.
我已修改您的代码以实现此结果:
I have modified your code to achieve this result:
def dY(y, x):
a = 0.001
yin = 1
C = 0.01
N = 1
dC = C/N
b1 = 0
y_diff = -np.copy(y)
y_diff[0] += yin
y_diff[1:] += y[:-1]
return (a/dC)*y_diff+b1*dC
我已经将部分y[i-1] - y[i]
编写为NumPy向量运算,并且对坐标y[0]
作了特殊情况(在您的表示法中为y1,但在Python中数组从0开始).
I have written the part y[i-1] - y[i]
as a NumPy vector operation and special cased the coordinate y[0]
(that is the y1 in your notation but arrays start at 0 in Python).
对于所有yi使用初始值为0的解决方案是
The solution, using an initial value of 0 for all yi is
x = np.linspace(0,20,1000)
y0 = np.zeros(4)
res = odeint(dY, y0, x)
plt.plot(x,res, '-')
这篇关于在Python中使用odeint实现积分数学方程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!