C: calculating the distance between two floats modulo 12

I need the function dist (a, b) // 0 โ‰ค a, b <12, which returns the shortest (absolute ie + ve) distance alammetry of the alam 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 be easily done with a little hack, I feel like there should be some kind of intuitive solution, it is possible to use fmod and modulo 6

+6
source share
3 answers

First, the optimal solution is non-trivial, he thought a little.

 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 

A complete list of codes is here: http://ideone.com/XxRIw

+11
source

If I read this correctly and a and b are not negative, they are less 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+ba, 12 ), fmod( 12+ab, 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+ab, 12 ); return diff <= 6 ? diff : 12-diff; } 
+6
source

Sort of

 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 a math library.

+4
source

Source: https://habr.com/ru/post/889489/


All Articles