2

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.

4
  • what did you try? There 2 possible answers, pick the lower one... whats the problem? Commented Nov 5, 2020 at 17:35
  • This thread might help: stackoverflow.com/questions/1878907/… Commented Nov 5, 2020 at 17:35
  • min((12+a-b)%12,(12-a+b)%12) Commented Nov 5, 2020 at 17:35
  • From 5 to 1 = 4. Can you elaborate this? Commented Nov 5, 2020 at 20:45

2 Answers 2

2

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?

Sign up to request clarification or add additional context in comments.

Comments

0

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

7 Comments

Well, I just noticed the requirement 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...
OP wants a and b doubles
@idclev463035818: Yeah I just noticed that, see my comment above.
yeah posted almost the same second. Its only a small change. fmod in place of %
Hope to see a more efficient way
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.