You are on page 1of 2

# %matplotlib inline

import math
import array as arr
import matplotlib.pyplot as plt
plt.style.use('default')
from scipy import *
from scipy import integrate
from scipy.integrate import ode
import numpy as np
fig = plt.figure(1)
ax=fig.add_subplot(111)

# Y chính xác
def exact_y(t):
exact = math.exp(-4*t)/2-math.exp(-2*t)/2+1
return exact

# Hàm dy/dt
def dydt(t, y):
return (-2*y + 2 - math.exp(-4*y))

# RungeKutta 4
def rungeKutta(t0, y0, t, h):
n = (int)((t - t0)/h)
y = y0
for i in range(1, n + 1):
k1 = h * dydt(t0, y)
k2 = h * dydt(t0 + 0.5 * h, y + 0.5 * k1)
k3 = h * dydt(t0 + 0.5 * h, y + 0.5 * k2)
k4 = h * dydt(t0 + h, y + k3)
# Update next value of y
y = y + (1.0 / 6.0)*(k1 + 2 * k2 + 2 * k3 + k4)
# Update next value of x
t0 = t0 + h
return y

# Euler
def Euler(t0, y0, t, h):
n = (int)((t - t0)/h)
y = y0
for i in range(1, n + 1):
k = h * dydt(t0, y)
y = y + k
t0 = t0 + h
return y

# Vector
t = 10.0
t0 = 0.0
y0 = 1.1
h = 0.1
n = (int)((t - t0)/0.001)
Y = arr.array('i',[y0])
YE = arr.array('i',[y0])
YR = arr.array('i',[y0])
T = arr.array('i',[t0])
for i in range(1, n+1):
T.append(T[i-1]+0.001)
Y.append(exact_y(T[i]))
YE.append(Euler(T[i-1], YE[i-1], T[i-1], h))
YE.append(Euler(T[i-1], YR[i-1], T[i-1], h))

plt.plot(T, Y, 'b-', label='Y chính xác')


plt.plot(T, YE, 'R-', label='Y theo Euler')
plt.plot(T, YR, 'y-', label='Y theo Runge Kutta 4')
plt.xlabel('t')
plt.ylabel('y(t)')
plt.legend(loc='best')
plt.title('Direction Field Plot for the System')
plt.show()

You might also like