\n",
"\n",
"\n"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"h = @. 4. ^(-1:-1:-8)\n",
"FD1 = []; FD2 = [];\n",
"for h in h\n",
" push!(FD1, (f(h)-f(0)) / h )\n",
" push!(FD2, (f(h)-f(-h)) / 2h ) \n",
"end\n",
"\n",
"pretty_table([h FD1 FD2],[\"h\",\"FD1\",\"FD2\"],backend=:html)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"All that's easy to see from this table is that FD2 appears to converge to the same result as FD1, but more rapidly. In each case $h$ is decreased by a factor of 4, so that the error is reduced by a factor of 4 in the first-order method and 16 in the second-order method."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"\n",
"\n",
"\n",
"\n",
"\n",
"
\n",
"
\n",
"
log_2(h)
\n",
"
error in FD1
\n",
"
error in FD2
\n",
"
\n",
"
\n",
"
-2
\n",
"
0.5316698672980729
\n",
"
-0.08589720009317459
\n",
"
\n",
"
\n",
"
-4
\n",
"
0.16675169931001355
\n",
"
-0.004443830592427034
\n",
"
\n",
"
\n",
"
-6
\n",
"
0.04278399066110605
\n",
"
-0.00027402935583697996
\n",
"
\n",
"
\n",
"
-8
\n",
"
0.010751437812063891
\n",
"
-1.711231996370799e-5
\n",
"
\n",
"
\n",
"
-10
\n",
"
0.002691131271080671
\n",
"
-1.0694634058339147e-6
\n",
"
\n",
"
\n",
"
-12
\n",
"
0.0006729843309356554
\n",
"
-6.684110775978525e-8
\n",
"
\n",
"
\n",
"
-14
\n",
"
0.00016825863274316788
\n",
"
-4.176695433955047e-9
\n",
"
\n",
"
\n",
"
-16
\n",
"
4.2065436150373614e-5
\n",
"
-2.7268942659475215e-10
\n",
"
\n",
"
\n",
"\n",
"\n"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"error_FD1 = @. exact_value - FD1 \n",
"error_FD2 = @. exact_value - FD2\n",
"\n",
"table = (n=Int.(log2.(h)),fd1=error_FD1,fd2=error_FD2)\n",
"pretty_table(table,[\"log_2(h)\",\"error in FD1\",\"error in FD2\"],backend=:html)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A graphical comparison can be clearer. On a log-log scale, the error should (roughly) be a straight line whose slope is the order of accuracy. However, it's conventional in convergence plots, to show $h$ _decreasing_ from left to right, which negates the slopes."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"image/svg+xml": [
"\n",
"\n"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"plot(h,abs.([error_FD1 error_FD2]),m=:o,label=[\"error FD1\" \"error FD2\"],\n",
" xflip=true, xaxis=(:log10,\"\\$h\\$\"), yaxis=(:log10,\"error in \\$f'(0)\\$\"),\n",
" title=\"Convergence of finite differences\", leg=:bottomleft)\n",
"\n",
"plot!(h,[h h.^2],l=:dash,label=[\"order1\" \"order2\"]) # perfect 1st and 2nd order"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Julia (faststart)",
"language": "julia",
"name": "julia-fast"
},
"language_info": {
"file_extension": ".jl",
"mimetype": "application/julia",
"name": "julia",
"version": "1.4.1"
}
},
"nbformat": 4,
"nbformat_minor": 4
}