{
"metadata": {
"name": "",
"signature": "sha256:f47016a75279357a782a179b0607ff4e124f9135a43b303a9a615a68cbfc219e"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "heading",
"level": 1,
"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",
"collapsed": false,
"input": [
"from numpy import zeros,exp\n",
"from matplotlib.pyplot import plot,xlabel,ylabel,legend"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 16
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"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'),loc='upper left')"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 20
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"First try with $\\alpha=1$."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"alpha = 1\n",
"h = 0.1\n",
"N = 20\n",
"ode(alpha,h,N)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "display_data",
"svg": [
"\n",
"\n",
"\n",
"\n"
],
"text": [
""
]
}
],
"prompt_number": 18
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now try with $\\alpha=-1$."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"alpha = -1\n",
"h = 0.1\n",
"N = 100\n",
"ode(alpha,h,N)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "display_data",
"svg": [
"\n",
"\n",
"\n",
"\n"
],
"text": [
""
]
}
],
"prompt_number": 19
}
],
"metadata": {}
}
]
}