{ "metadata": { "name": "", "signature": "sha256:22fa136c5dd7dbbfe30c4075a0c8fe13b37cca336f5cad8a878e8335fc9619c4" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "heading", "level": 1, "metadata": {}, "source": [ "Error due to subtraction" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Consider computing\n", "$$\n", "x=10^{-8}, \\qquad y = 1 - \\cos(x)\n", "$$" ] }, { "cell_type": "code", "collapsed": false, "input": [ "from numpy import sin,cos" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 1 }, { "cell_type": "code", "collapsed": false, "input": [ "x = 1.0e-8\n", "y = 1.0 - cos(x)\n", "print \"%24.14e\" % y" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ " 0.00000000000000e+00\n" ] } ], "prompt_number": 8 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Because of roundoff error, the result is zero. But mathematically we have the equivalent expression\n", "$$\n", "z = 2 \\sin^2(x/2)\n", "$$\n", "which does not involve subtraction of nearly equal quantities." ] }, { "cell_type": "code", "collapsed": false, "input": [ "z = 2.0*sin(0.5*x)**2\n", "print \"%24.14e\" % z" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ " 5.00000000000000e-17\n" ] } ], "prompt_number": 10 }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] } ], "metadata": {} } ] }