Take for example time:
If we take a 12-hour clock, we'd get the following results
- from 1 to 5 = 4
- from 5 to 1 = 4
- from 11 to 1 = 2
- from 1 to 11 = 2
What is the most efficient way to do that?
Assuming the values are doubles.
Without using modulo operations. fabs is cheap.
double closest_dist_in_cycle(double a, double b, double cycle){ double result = std::fabs(a - b); return std::min(result, cycle - result); } Reference:
How would fabs(double) be implemented on x86? Is it an expensive operation?
With mod being your cycle, and under the assumption that both input values are smaller than mod, you can use:
int x = std::min((mod + a - b) % mod, (mod - a + b) % mod); Assuming the values are doubles, which of course makes this solution irrelevant, since the modulo operator % is defined only for integers. Not sure how exactly a cyclic system would be defined over non-integers though...a and b doublesfmod in place of %
min((12+a-b)%12,(12-a+b)%12)