Sujet
import numpy as np
import matplotlib.pyplot as plt
## Euler
def Euler(F,t0,tf,y0,n):
t=t0
y=y0
h=(tf-t0)/n
abcisses=[t0]
ordonnees=[y0]
for i in range(n):
y += h*F(t,y)
t += h
abcisses.append(t)
ordonnees.append(y)
return abcisses,ordonnees
a,o = Euler(lambda t,y: y,0,10,1,1000)
o2 = np.exp(a)
plt.plot(a,o)
plt.plot(a,o2)
plt.legend(["Euler","Exacte"])
plt.show()
## Euler systeme
def Euler_systeme(F,G,t0,tf,x0,y0,n):
t=t0
x=x0
y=y0
h=(tf-t0)/n
temps=[t0]
Lx=[x0]
Ly=[y0]
for i in range(n):
x,y = x+h*F(t,x,y), y + h*G(t,x,y)
t += h
temps.append(t)
Lx.append(x)
Ly.append(y)
return temps, Lx, Ly
# x et y en fonction du temps
t,x,y = Euler_systeme(lambda t,x,y:x*(3-2*y),lambda t,x,y: y*(-4+x),0,10,10,1,500000)
plt.plot(t,x); plt.plot(t,y)
plt.show()
## Euler EDO2
def Euler2(F,t0,tf,y0,dy0,n):
f = lambda t,x,y: F(t,y,x)
g = lambda t,x,y: x
t,x,y = Euler_systeme(f,g,t0,tf,dy0,y0,n)
return [t,y]
t,y = Euler2(lambda t,y,dy: -y,0,50,1,0,1000)
_,y2 = Euler2(lambda t,y,dy: -np.sin(y),0,50,1,0,1000)
plt.plot(t,y)
plt.plot(t,y2)
plt.show()
## RK4
def RK4(F,t0,tf,y0,n):
t=t0
y=y0
h=(tf-t0)/n
abcisses=[t0]
ordonnees=[y0]
for i in range(n):
K1 = h*F(t,y)
K2 = h * F(t+h/2,K1/2+y)
K3 = h * F(t+h/2,K2/2+y)
K4 = h * F(t+h,K3+y)
y += (1/6)*(K1+2*K2+2*K3+K4)
t += h
abcisses.append(t)
ordonnees.append(y)
return abcisses,ordonnees
a,o = RK4(lambda t,y: np.cos(t)-y,0,100,1,1000)
plt.plot(a,o)
plt.show()
## odeint
from scipy.integrate import odeint
t = np.linspace(0,10,1000)
plt.plot(t,odeint(lambda y,t: np.cos(t)-y,1,t)); plt.show()
l = odeint(lambda y,t: np.array([y[0]*(3-2*y[1]), y[1]*(-4+y[0])]),np.array([10,1]),t)
plt.plot(l[:,0],l[:,1]); plt.show()
plt.plot(t,odeint(lambda y,t: np.array([-np.sin(y[1]),y[0]]),np.array([1,0]),t)[:,1]);
plt.show()
## Lorenz
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
def FLorenz(v,t,sigma=10,beta=2.66,rho=30):
xp = sigma*(v[1]-v[0])
yp = rho*v[0] - v[1] - v[0]*v[2]
zp = v[0]*v[1] - beta*v[2]
return [xp,yp,zp]
t = np.linspace(0,50,10000)
v = odeint(FLorenz, [20,0,0],t)
ax.plot(v[:,0],v[:,1],v[:,2],linewidth=.9)
v = odeint(FLorenz, [10,0,0],t)
ax.plot(v[:,0],v[:,1],v[:,2],linewidth=.9)
v = odeint(FLorenz, [0.1,0,0],t)
ax.plot(v[:,0],v[:,1],v[:,2],linewidth=.9)
plt.show()