#!/usr/bin/env python # coding: utf-8 # # Example of finite precision # Let us evaluate # $$ # y = x^3 - 3 x^2 + 3 x - 1 # $$ # in single precision. Note that it can also be written as # $$ # y = (x-1)^3 # $$ # In[18]: get_ipython().run_line_magic('matplotlib', 'inline') get_ipython().run_line_magic('config', "InlineBackend.figure_format = 'svg'") import numpy as np import matplotlib.pyplot as plt # We evaluate in the interval $[0.99,1.01]$. # In[19]: x = np.linspace(0.99,1.01,50,dtype=np.float32) y = x**3 - 3.0*x**2 + 3.0*x - 1.0 plt.plot(x,y,'-o',x,(x-1)**3) plt.xlabel('x') plt.ylabel('y') plt.legend(('Single precision','Exact')); # Now, let us do it in double precision # In[20]: x = np.linspace(0.99,1.01,50,dtype=np.float64) y = x**3 - 3.0*x**2 + 3.0*x - 1.0 plt.plot(x,y,'-o',x,(x-1)**3) plt.xlabel('x') plt.ylabel('y') plt.legend(('Double precision','Exact'));