开发者

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 al开发者_开发百科a 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


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


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;
}


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.


I think we can find the answer without any comparison, or branching. A one-liner. (IMO the most elegant way)

float dist(float a, float b){
    return abs(5.5-((b-(a-5.5))%12.0))
}

5.5 here is the middle point of the number line from 0 to 11.

After benchmarking though, it seems to be maybe very slightly slower than just doing it through MIN.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜