How to put initial condition of ODE at a specific time point using odeint in Python?
So I have y(0) = 5 as initial condition, following code works::
JavaScript
x
25
25
1
import numpy as np
2
from scipy.integrate import odeint
3
import matplotlib.pyplot as plt
4
5
# function that returns dy/dt
6
def model(y,t):
7
k = 0.3
8
dydt = -k * y
9
return dydt
10
11
# initial condition
12
y0 = 5
13
14
# time points
15
t = np.linspace(0,20)
16
17
# solve ODE
18
y = odeint(model,y0,t)
19
20
# plot results
21
plt.plot(t,y)
22
plt.xlabel('time')
23
plt.ylabel('y(t)')
24
plt.show()
25
I wanna see the graph in both negative and positive time line.
So I change t = np.linspace(0,20)
to t = np.linspace(-5,20)
, but then the initial condition is taken as y(-5) = 5.
How to solve this?
Advertisement
Answer
I do not think you can, according to the docs
But you can solve for positive and negative t
‘s separately and then stich them together. Replace the relevant lines with
JavaScript
1
11
11
1
tp = np.linspace(0,20)
2
tm = np.linspace(0,-5)
3
4
# solve ODE
5
yp = odeint(model,y0,tp)
6
ym = odeint(model,y0,tm)
7
8
# stich together; note we flip the time direction with [::-1] construct
9
t = np.concatenate([tm[::-1],tp])
10
y = np.concatenate([ym[::-1],yp])
11