Python Program to Solve ODE's
Write a program to solve linear differential equation using SciKit and plotting the result in matplotlib
In this example we will take a simple first order linear differential equation and try to solve it using scipy.integrate module.
The Liner ODE is given below;
With the initial conditions are; y(t=0)=4 and k=0.1
The Python code first imports the needed Numpy, Scipy, and Matplotlib packages. The model, initial conditions, and time points are defined as inputs to scipy.integrate to numerically calculate y(t).
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
# function that returns dy/dt
def model(y,t,k):
dydt = -k * y
return dydt
# initial condition of y at t=0
y0 = 4
# time points total 30 points taken
t = np.linspace(0,30)
# solve the ordinary differential equation for various values of k
k = 0.1
y1 = odeint(model,y0,t,args=(k,))
k = 0.2
y2 = odeint(model,y0,t,args=(k,))
k = 0.3
y3 = odeint(model,y0,t,args=(k,))
k = 0.4
y4 = odeint(model,y0,t,args=(k,))
k = 0.5
y5 = odeint(model,y0,t,args=(k,))
# plot the results in the same plot
plt.plot(t,y1,'r-',linewidth=2,label='k=0.1')
plt.plot(t,y2,'b--',linewidth=2,label='k=0.2')
plt.plot(t,y3,'c--',linewidth=2,label='k=0.3')
plt.plot(t,y4,'m--',linewidth=2,label='k=0.4')
plt.plot(t,y5,'g:',linewidth=2,label='k=0.5')
plt.xlabel('time')
plt.ylabel('y(t)')
plt.legend()
plt.show()
The output will show the plot of time (t) on abscissa y(t) on ordinate
This is the output for
This is the output for