Skip to content

Instantly share code, notes, and snippets.

@gmaze
Created December 11, 2017 12:29
Show Gist options
  • Save gmaze/a1009b0cb314885d8e148d7df426de6e to your computer and use it in GitHub Desktop.
Save gmaze/a1009b0cb314885d8e148d7df426de6e to your computer and use it in GitHub Desktop.
Demonstrate the different behaviours of numpy arange and linspace with regard to truncation error
import numpy as np
eps = np.finfo(np.float64).eps
print "This is epsilon:", eps
print "\nnumpy.arange"
dX = 0.1
X = np.arange(34.,38.,dX)
udX = np.unique(np.diff(X))
print "Unique dX:", udX
trunc_err = (np.diff(X)/dX-1)/eps
print "Float truncation error (as N x eps) with arange:", trunc_err
print "Mean float truncation error (as N x eps) with arange:", np.mean(trunc_err)
print "\nnumpy.linspace"
X = np.linspace(34.,38.,(38-34)/dX+1)
udX = np.unique(np.diff(X))
print "Unique dX:", udX
trunc_err = (np.diff(X)/dX-1)/eps
print "Float truncation error (as N x eps) with linspace:", trunc_err
print "Mean float truncation error (as N x eps) with linspace:", np.mean(trunc_err)
@gmaze
Copy link
Author

gmaze commented Dec 11, 2017

This code will print the following:

This is epsilon: 2.22044604925e-16

numpy.arange
Unique dX: [ 0.1]
Float truncation error (as N x eps) with arange: [ 64.  64.  64.  64.  64.  64.  64.  64.  64.  64.  64.  64.  64.  64.  64.
  64.  64.  64.  64.  64.  64.  64.  64.  64.  64.  64.  64.  64.  64.  64.
  64.  64.  64.  64.  64.  64.  64.  64.  64.]
Mean float truncation error (as N x eps) with arange: 64.0

numpy.linspace
Unique dX: [ 0.1  0.1]
Float truncation error (as N x eps) with linspace: [  64.   64. -256.   64.   64.   64.   64. -256.   64.   64.   64.   64.
 -256.   64.   64.   64.   64. -256.   64.   64.   64.   64. -256.   64.
   64.   64.   64. -256.   64.   64.   64.   64. -256.   64.   64.   64.
   64. -256.   64.   64.]
Mean float truncation error (as N x eps) with linspace: 0.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment