Corrige de l’equation 1
1import numpy as np
2import scipy.integrate as sp
3from scipy.optimize import fsolve
4import matplotlib.pyplot as plt
5def Euler_ordre1_explicit(F,a,b,y0,n):
6y,t,Y,T,h=y0,a,[y0],[a],(b-a)/n
7for iin range(n):
8y=y+h*F(t,y)
9t=t+h
10 Y.append(y)
11 T.append(t)
12 return T,Y
13 def Heun(F,a,b,y0,n):
14 y,t,Y,T,h=y0,a,[y0],[a],(b-a)/n
15 for iin range(n):
16 x=y+(h/2)*F(t,y)
17 y=y+h*F(t+(h/2), x)
18 t=t+h
19 Y.append(y)
20 T.append(t)
21 return T,Y
22 def RK4(F,a,b,y0,n):
23 y,t,Y,T,h=y0,a,[y0],[a],(b-a)/n
24 for iin range(n):
25 x1=h*F(t,y)
26 x2=h*F(t+h/2,y+x1/2)
27 x3=h*F(t+h/2,y+x2/2)
28 x4=h*F(t+h,y+x3)
29 y=y+(1/6)*(x1+2*x2+2*x3+x4)
30 t=t+h
31 Y.append(y)
32 T.append(t)
33 return T,Y
34 def F(t,y):
35 return -y+np.cos(t)
36 def SolExacte(T):
37 Y=[]
38 for xin T:
39 Y.append( 0.5*(np.cos(x)+np.sin(x)+5*np.exp(-x)))
40 return Y
41 T1,Y1=Euler_ordre1_explicit(F,0,1,3,50)
42 T2,Y2=Heun(F,0,1,3,50)
43 T3,Y3=RK4(F,0,1,3,50)
44 Y4=sp.odeint(F,3,T1)
45 Y5=SolExacte(T1)
46
47 plt.plot(T1,Y1,’b-.’,label=’Euler␣explicite’)
48 plt.plot(T1,Y5,’g-s’,label=’Solution␣exacte’)
49 plt.plot(T1,Y2,’y-h’,label=’Heun’)
50 plt.plot(T1,Y3,’ro’,label=’RK4’)
51 plt.plot(T1,Y3,’c-x’,label=’odeint’)
9
´ ´
52 plt.grid()
53 plt.legend()
54 plt.show()