P10.1.2Determining the machine-epsilon
Write a function to determine the machine epsilon of a numerical data type (float, np.float64, np.longdouble, np.float128 (if it exists on your system), int, etc.).
Show solution
For example:
machineepsilon
def get_epsilon(dtype):
eps = dtype(1)
while dtype(1) + dtype(eps) != dtype(1):
previous_eps = eps
eps = dtype(eps) / dtype(2)
return previous_eps
print(int, get_epsilon(int))
print(float, get_epsilon(float))
import numpy as np
print(np.longdouble, get_epsilon(np.longdouble))
Gives, on my system:
<class 'int'> 1
<class 'float'> 2.220446049250313e-16
<class 'numpy.longdouble'> 2.220446049250313e-16
On my system, NumPy's longdouble data type is just a regular double-precision floating point number. On other systems, this could be a 96-bit or 128-bit quantity instead, giving higher precision.