{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Error due to subtraction" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Consider computing\n", "$$\n", "x = 10^{-8}, \\qquad y = \\sqrt{1+x^2} - 1\n", "$$" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " 0.0000000000e+00\n" ] } ], "source": [ "from math import sqrt\n", "x = 1.0e-8\n", "y = sqrt(1.0 + x**2) - 1.0\n", "print(\"%20.10e\" % y)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The result is zero due to round-off error. An equivalent expression is\n", "$$\n", "y = \\frac{x^2}{\\sqrt{1 + x^2} + 1}\n", "$$" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " 5.0000000000e-17\n" ] } ], "source": [ "y = x**2/(sqrt(1.0+x**2) + 1.0)\n", "print(\"%20.10e\" % y)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.6" } }, "nbformat": 4, "nbformat_minor": 1 }