Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: Calculating the distance between 2 floats modulo 12

Tags:

c

modulo

distance

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

like image 286
P i Avatar asked May 31 '11 19:05

P i


3 Answers

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

like image 129
P i Avatar answered Nov 12 '22 17:11

P i


If I read that correctly, a and b aren't negative, and they are smaller than 12.

#include <math.h>
#include <stdio.h>

double min( double a, double b ) {
   return a < b ? a : b;
}

double dist( double a, double b ) {
   return min( 
      fmod( 12+b-a, 12 ),
      fmod( 12+a-b, 12 )
   );
}

int main() {
   printf("%f\n", dist(1, 2));
   printf("%f\n", dist(2, 1));
   printf("%f\n", dist(11, 0));
   printf("%f\n", dist(0, 11));
   printf("%f\n", dist(0.5, 11.5));
   return 0;
}

which simplifies to

double dist( double a, double b ) {
   double diff = fmod( 12+a-b, 12 );
   return diff <= 6 ? diff : 12-diff;
}
like image 45
ikegami Avatar answered Nov 12 '22 18:11

ikegami


Something like

float dist( float a, float b ){

   float amod, bmod;

   amod = fmod( a, 12 );
   bmod = fmod( b, 12 );

   if( amod < bmod ) return dist( bmod, amod );

   return min( amod-bmod, bmod-amod+12 );

}

Using the math library.

like image 5
trutheality Avatar answered Nov 12 '22 18:11

trutheality