pythonnumpynumpy-ndarray

Find absolute difference value between elements using just NumPy array operations


a = np.array([101,105,90,102,90,10,50])
b = np.array([99,110,85,110,85,90,60])

expected result = np.array([2,5,5,8,5,20,10])

How can I find minimum absolute difference value between elements using just numpy operations; with modulus of 100 if two values are across 100.


Solution

  • The answer by Derek Roberts with numpy.minimum is almost correct. However, since the input values can be greater than 100, they should first be rescaled to 0-100 with %100 (mod). I'm adding an extra pair of values to demonstrate this:

    a = np.array([101,105,90,102,90,10,50,1001])
    b = np.array([99,110,85,110,85,90,60,2])
    
    x = abs(a%100-b%100)
    np.minimum(x, 100-x)
    

    Generic computation:

    M = 100
    x = abs(a%M-b%M)
    np.minimum(x, M-x)
    

    Output:

    array([ 2,  5,  5,  8,  5, 20, 10,  1])