cdistancemodulo

C: Calculating the distance between 2 floats modulo 12


I require a function dist( a, b ) // 0 ≤ a,b < 12 which returns the shortest (absolute ie +ve) distance ala clock arithmetic, using modulo 12.

So for example,

dist( 1, 2 )
 = dist( 2, 1 )
 = dist( 11, 0 )
 = dist( 0, 11 )
 = dist( 0.5, 11.5 )
 = 1

EDIT: while this can easily be done with a bit of hacking around, I feel that there must be some intuitive solution, may be using fmod and modulo 6


Solution

  • Firstly, an optimal solution is nontrivial, it took a little thinking.

    float distMod12(float a,float b)
    {
        float diff = fabs( b - a );
        return ( diff < 6 ) ? diff : 12 - diff;
    }
    

    EDIT: Alternatively,

        return MIN( diff, 12 - diff ); // needs a MIN function
    

    Complete code listing here: http://ideone.com/XxRIw