Codigo.
import numpy as np
import matplotlib.pyplot as plt
def f(t,y): return y
def rk4(t0,y0,dt,f):
k1 = f(t0, y0)
k2 = f(t0 + dt / 2.0, y0 + dt * k1 / 2.0)
k3 = f(t0 + dt / 2.0, y0 + dt * k2 / 2.0)
k4 = f(t0 + dt, y0 + dt * k2)
y = y0 + (dt / 6.0) * (k1 + 2.0 * k2 + 2.0 * k3 + k4)
return y
def euler(t0, y0, dt, f):
f0 = f(t0, y0)
y = y0 + dt * f0
return y
def exact_sol(t): return np.exp(t)
if __name__=='__main__':
tmax = 5
plt.figure(figsize=(10,10))
for n, c in zip([10,100], ['red','blue']):
ys_rk4 = [1]
ys_euler = [1]
ts = np.linspace(0,tmax,n)
dt = ts[1] - ts [0]
for i in range(n-1):
u_rk4 = rk4(ts[i], ys_rk4[i], dt,f)
u_euler = euler(ts[i], ys_euler[i], dt, f)
ys_rk4.append(u_rk4)
ys_euler.append(u_euler)
plt.plot(ts, ys_euler, '--', color=c, label='Euler dt = {}'.format(round(dt,3)))
plt.plot(ts, ys_rk4, color=c, label='RK4 dt = {}'.format(round(dt,3)))
plot_text_size = 20
plt.plot(ts, exact_sol(ts), '-k', label='exact')
plt.xticks(fontsize=plot_text_size)
plt.yticks(fontsize=plot_text_size)
plt.legend(fontsize = plot_text_size)
plt.show()
tmax = 100
dt_arr = np.arange(0.0001, 0.5, 0.0001)
error_rk4 = []
error_euler = []
for dt in dt_arr:
ys_rk4 = [1]
ys_euler = [1]
ts = np.arange(0, tmax, dt)
for i in range(len(ts)):
u_rk4 = rk4(ts[i], ys_rk4[i], dt, f)
u_euler = euler(ts[i], ys_euler[i], dt, f)
ys_rk4.append(u_rk4)
ys_euler.append(u_euler)
ys_exact = exact_sol(ts)
error_rk4.append(np.abs(ys_rk4[-1]-ys_exact[-1]))
error_euler.append(np.abs(ys_euler[-1]-ys_exact[-1]))
plt. figure(figsize=(10,8))
plot_text_size = 20
plt.plot(dt_arr, error_rk4, label='RK4')
plt.plot(dt_arr, error_euler, label='Euler')
plt.plot(dt_arr[:-4900],error_rk4[:-4900], '-*r')
plt.xticks(fontsize=plot_text_size)
plt.yticks(fontsize=plot_text_size)
plt.legend(fontsize=plot_text_size)
plt.yscale('log')
plt.xscale('log')
plt.show()
¿Quieres ver más aportes, preguntas y respuestas de la comunidad?