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::
import numpy as np from scipy.integrate import odeint import matplotlib.pyplot as plt # function that returns dy/dt def model(y,t): k = 0.3 dydt = -k * y return dydt # initial condition y0 = 5 # time points t = np.linspace(0,20) # solve ODE y = odeint(model,y0,t) # plot results plt.plot(t,y) plt.xlabel('time') plt.ylabel('y(t)') plt.show()
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?
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
tp = np.linspace(0,20) tm = np.linspace(0,-5) # solve ODE yp = odeint(model,y0,tp) ym = odeint(model,y0,tm) # stich together; note we flip the time direction with [::-1] construct t = np.concatenate([tm[::-1],tp]) y = np.concatenate([ym[::-1],yp])