pythonnumpyepsilon

python numpy machine epsilon


I am trying to understand what is machine epsilon. According to the Wikipedia, it can be calculated as follows:

def machineEpsilon(func=float):
    machine_epsilon = func(1)
    while func(1)+func(machine_epsilon) != func(1):
        machine_epsilon_last = machine_epsilon
        machine_epsilon = func(machine_epsilon) / func(2)
    return machine_epsilon_last

However, it is suitable only for double precision numbers. I am interested in modifying it to support also single precision numbers. I read that numpy can be used, particularly numpy.float32 class. Can anybody help with modifying the function?


Solution

  • An easier way to get the machine epsilon for a given float type is to use np.finfo():

    print(np.finfo(float).eps)
    # 2.22044604925e-16
    
    print(np.finfo(np.float32).eps)
    # 1.19209e-07