[英]Solving a Differential equation in ODEINT
I am going crazy and I cannot figure out what is wrong with my code.我快疯了,我无法弄清楚我的代码有什么问题。 I am trying to solve a differential equation using ODEINT, but for some reasons it does not work as it supposed to, here is the question, it is a matrix of 5: equation
我正在尝试使用 ODEINT 求解微分方程,但由于某些原因它不能正常工作,这是问题,它是一个 5 矩阵:方程
def model(y,t):
#constant
u = 7
#l(t)
l = 8.924 \
- 1.584 * cos(math.radians((pi*t) / 1.51))\
+ 7.897 * sin(math.radians((pi*t) / 3.02))\
- 10.434 * cos(math.radians((pi*t) / 4.53))\
+ 4.293 * cos(math.radians((pi*t) / 6.04))
p0 = y[0]
p1 = y[1]
p2 = y[2]
p3 = y[3]
p4 = y[4]
#Differential equations
dp0dt = -l*p0 + u*p1
dp1dt = l*p0 - (l+u)*p1 + u*p2
dp2dt = l*p1 - (l+u)*p2 + u*p3
dp3dt = l*p2 - (l+u)*p3 + u*p4
dp4dt = l*p3 - u*p4
return dp0dt, dp1dt, dp2dt, dp3dt, dp4dt
and here is the ODEINT and plot codes:这是 ODEINT 和绘图代码:
#initial condition
y0 = [1,0,0,0,0]
#time
time = np.linspace(0,8)
#solve ode
y = odeint(model,y0,time)
p0 = y[:,0]
p1 = y[:,1]
p2 = y[:,2]
p3 = y[:,3]
p4 = y[:,4]
#plot
plt.plot(time,p4)
plt.xlabel('time')
plt.ylabel('p4')
plt.show()
The main problem is your use of math.radians
in definiing function l
.主要问题是您在定义函数
l
使用math.radians
。 In math, almost invariably, arguments to cos
etc are given in radians already.在数学中,几乎总是以弧度给出
cos
等的参数。 And if they involve pi
then for sure they are in radians.如果它们涉及
pi
那么肯定它们是弧度。
so I rewrote that bit as所以我把那一点改写为
#l(t)
l = 8.924 \
- 1.584 * math.cos(math.pi*t / 1.51)\
+ 7.897 * math.sin(math.pi*t / 3.02)\
- 10.434* math.cos(math.pi*t / 4.53)\
+ 4.293 * math.cos(math.pi*t / 6.04)
also your idents in the model
function were wrong -- I took the liberty to fix them in the question as I assumed this was a copy and paste issue not your real code issue你在
model
函数中的标识也是错误的——我冒昧地在问题中修复它们,因为我认为这是一个复制和粘贴问题,而不是你真正的代码问题
with this fix I get this graph from your code通过这个修复,我从你的代码中得到了这个图
which to me looks kind of what you want对我来说这看起来像你想要的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.