1. 程式人生 > >利用python畫微分方程(組)的數值曲線

利用python畫微分方程(組)的數值曲線

# This is a simple numerical example using matplotlib to simulate differential equatons, here we take y'= -sin(t), y(0)= 1. It's easy to compare with the standard plot method.
# Filename: sin.py

# Author: Qiang Xiao
# Time: 2015-06-19

import matplotlib.pyplot as plt    #matplotlib deal with plotting
import numpy as np    #numerical computation

t0= 0    #start point
te= 10    #end point
delta= 0.1    #step length

y= np.zeros(101)    #declare funtion value
dy= np.zeros(101)    #declare derivative value
y[0]= 1;    #initial value

for i in np.arange(100):
    dy[i]= -np.sin(i*delta);    #computing the first derivative
    y[i+1]= y[i]+ delta*dy[i];    #estimating function value by differential property

time= np.arange(t0,te+delta,delta);    

plt.plot(time, y,'r') #plotting
    
sint= [np.cos(t) for t in time]
plt.plot(time,sint,'b')
plt.xlabel('time t')
plt.ylabel('cos')
plt.title('Plotting differential equations.')
plt.legend(('cos_definite','cos_standard'))
plt.ylim([-1.2,1.2])
plt.show()