{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Example of finite precision"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let us evaluate\n",
"$$\n",
"y = x^3 - 3 x^2 + 3 x - 1\n",
"$$\n",
"in single precision. Note that it can also be written as \n",
"$$\n",
"y = (x-1)^3\n",
"$$"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [],
"source": [
"%matplotlib inline\n",
"%config InlineBackend.figure_format = 'svg'\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We evaluate in the interval $[0.99,1.01]$."
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"data": {
"image/svg+xml": [
"\n",
"\n",
"\n",
"\n"
],
"text/plain": [
""
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"x = np.linspace(0.99,1.01,50,dtype=np.float32)\n",
"y = x**3 - 3.0*x**2 + 3.0*x - 1.0\n",
"plt.plot(x,y,'-o',x,(x-1)**3)\n",
"plt.xlabel('x')\n",
"plt.ylabel('y')\n",
"plt.legend(('Single precision','Exact'));"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now, let us do it in double precision"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"data": {
"image/svg+xml": [
"\n",
"\n",
"\n",
"\n"
],
"text/plain": [
""
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"x = np.linspace(0.99,1.01,50,dtype=np.float64)\n",
"y = x**3 - 3.0*x**2 + 3.0*x - 1.0\n",
"plt.plot(x,y,'-o',x,(x-1)**3)\n",
"plt.xlabel('x')\n",
"plt.ylabel('y')\n",
"plt.legend(('Double precision','Exact'));"
]
}
],
"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": 2
}