{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# ODE: example of unstable scheme"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Consider the ODE\n",
"$$\n",
"y' = \\alpha y, \\qquad y(0) = 1\n",
"$$\n",
"whose exact solution is\n",
"$$\n",
"y(t) = \\exp(\\alpha t)\n",
"$$\n",
"Consider the simple scheme\n",
"$$\n",
"y_0 = 1, \\qquad y_1 = \\exp(\\alpha h), \\qquad\n",
"\\frac{y_{i+1} - y_{i-1}}{2h} = \\alpha y_i, \\qquad i=1,2,\\ldots\n",
"$$\n",
"i.e., with $a = 2\\alpha h$, iterative scheme is\n",
"$$\n",
"y_{i+1} = a y_i + y_{i-1}, \\qquad i=1,2,\\ldots\n",
"$$"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [],
"source": [
"%matplotlib inline\n",
"%config InlineBackend.figure_format = 'svg'\n",
"from numpy import zeros,exp\n",
"from matplotlib.pyplot import plot,xlabel,ylabel,legend"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The following function performs the solution of the ode."
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [],
"source": [
"def ode(alpha,h,N):\n",
" \"\"\"\n",
" h = step size\n",
" N = number of steps to take\n",
" \"\"\"\n",
" y = zeros(N)\n",
" t = zeros(N)\n",
" t[0], y[0] = 0, 1\n",
" t[1], y[1] = h, exp(alpha*h)\n",
" a = 2.0*alpha*h\n",
" for i in range(1,N-1):\n",
" y[i+1] = a*y[i] + y[i-1]\n",
" t[i+1] = t[i] + h\n",
" ye = exp(alpha*t)\n",
" plot(t,y,'o-',t,ye,'r-')\n",
" xlabel('t')\n",
" ylabel('y')\n",
" legend(('Numerical','Exact'))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"First try with $\\alpha=1$."
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"data": {
"image/svg+xml": [
"\n",
"\n",
"\n",
"\n"
],
"text/plain": [
"