{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# ODE using forward Euler"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Conside the ODE\n",
"$$\n",
"y' = -y + 2 \\exp(-t) \\cos(2t)\n",
"$$\n",
"with initial condition\n",
"$$\n",
"y(0) = 0\n",
"$$\n",
"The exact solution is\n",
"$$\n",
"y(t) = \\exp(-t) \\sin(2t)\n",
"$$"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"%matplotlib inline\n",
"%config InlineBackend.figure_format = 'svg'\n",
"import numpy as np\n",
"from matplotlib import pyplot as plt"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Right hand side function"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"def f(t,y):\n",
" return -y + 2.0*np.exp(-t)*np.cos(2.0*t)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Exact solution"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"def yexact(t):\n",
" return np.exp(-t)*np.sin(2.0*t)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This implements Euler method\n",
"$$\n",
"y_n = y_{n-1} + h f(t_{n-1},y_{n-1})\n",
"$$"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"def euler(t0,T,y0,h):\n",
" N = int((T-t0)/h)\n",
" y = np.zeros(N)\n",
" t = np.zeros(N)\n",
" y[0] = y0\n",
" t[0] = t0\n",
" for n in range(1,N):\n",
" y[n] = y[n-1] + h*f(t[n-1],y[n-1])\n",
" t[n] = t[n-1] + h\n",
" return t, y"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Solve for a given h"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"image/svg+xml": [
"\n",
"\n",
"\n",
"\n"
],
"text/plain": [
"