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
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:
#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()
it should plot this: p4
The main problem is your use of math.radians
in definiing function l
. In math, almost invariably, arguments to cos
etc are given in radians already. And if they involve pi
then for sure they are in radians.
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
with this fix I get this graph from your code
which to me looks kind of what you want
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.