{ "cells": [ { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": true }, "outputs": [], "source": [ "%plot gnuplot" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$f'(x_0) \\approx \\frac{f(x_0 + h) -f(x_0)}{h} + O(h)$\n", "\n", "error = $|f'(x_0) - \\frac{f(x_0 + h) -f(x_0)}{h}| \\approx O(h)$ \n" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "c1 =\n", "\n", " 1.002263431950136 -0.740850628132612\n", "\n" ] } ], "source": [ "clear all\n", "format long\n", "f = @(x) sin(x);\n", "x0=1.2;\n", "f0=sin(x0);\n", "fp=cos(x0);\n", "i=-6:0.5:0;\n", "h=10.^i;\n", "err=abs(fp-(sin(x0+h)-f0)./h);\n", "subplot(1,2,1)\n", "loglog(h,err,'-*');\n", "xlabel('h')\n", "ylabel('error = |f(x_0) (exact) - f(x_0) (numeric)|')\n", "c1 = polyfit(log(h),log(abs(err)),1)\n", "hold on\n", "subplot(1,2,2)\n", "\n", "plot(log(h), c1(1)*log(h)+c1(2))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

c1(1) = 1.002263431950136 means the order of error is $\\approx 1$.

\n", "
\n", "\"Derivative\"" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": false }, "outputs": [], "source": [ "f = @(x) sin(x);\n", "x0 = 0:0.001:20;\n", "f0 = f(x0);\n", "J = length(f0);\n", "dx=x0(2)-x0(1);\n", "slope = [(f0(2:J)-f0(1:J-1))/dx, (f0(J)-f0(J-1))/dx]; % Forward\n", "x1 = 0:0.5:20;\n", "figure;\n", "plot(x0,slope,'r',x1,cos(x1),'ob')\n", "legend('exact','numerical')" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "\"Derivative\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Try yourself\n", "Find second derivative, $f''(x_0) \\approx \\frac{f(x_0 + h) -2 f(x_0) +f(x_0 - h)}{h^2} + O(h^2)$.
\n", "Verify the order of error. " ] } ], "metadata": { "kernelspec": { "display_name": "Octave", "language": "octave", "name": "octave" }, "language_info": { "file_extension": ".m", "help_links": [ { "text": "MetaKernel Magics", "url": "https://github.com/calysto/metakernel/blob/master/metakernel/magics/README.md" } ], "mimetype": "text/x-octave", "name": "octave", "version": "0.16.1" } }, "nbformat": 4, "nbformat_minor": 1 }