-3

I need to make an efficient function that matches this footprint:

public static double NearestAngle(this double currentAngle, double targetAngle);

where the return value is targetAngle +/- n*2pi. The return value should minimize the absolute difference between itself and currentAngle. How can I do this efficiently in C#? I want to avoid loops as the inputs can be many circles apart.

Brannon
  • 5,324
  • 4
  • 35
  • 83
  • 2
    Can you be more clear about the return value? – dckuehn May 07 '14 at 20:48
  • Why the n in n*2pi ? Aren't you looking for a number in [0..2pi) ? Or can current or target be > 2pi? – H H May 07 '14 at 20:51
  • Can you work in degrees instead of radians? It's hard to work with irrational numbers in code. – Bobson May 07 '14 at 20:51
  • No, I'm not looking for a number [0..2pi). If my `currentAngle == -6` and `targetAngle == 0` I want to return -2pi. – Brannon May 07 '14 at 20:52
  • Your terminology is confusing - you want the return value to be close to currentAngle, not targetAngle??? – mbeckish May 07 '14 at 20:54
  • 2
    @Brannon That's moving the current angle away from the target angle. Should it not be moving *towards* the target angle? If not, what is the point in including the target angle at all? – Servy May 07 '14 at 20:55
  • I want to move targetAngle toward currentAngle without changing targetAngle (aka, keeping it +/-2pi of its original value). – Brannon May 07 '14 at 20:58
  • 1
    You confuse more and more. _without changing_ != _keeping it in +/-2pi_ – H H May 07 '14 at 20:59
  • 1
    @Brannon `+/- n*2*pi` is NOT the same as "within +/- 2*pi". Please take one more stab at editing your question to state eactly what you mean. – mbeckish May 07 '14 at 21:03
  • I don't know how to phrase the title any better. The question says exactly what I mean, and it was sufficient to get the correct answer. Ideas for a better title? – Brannon May 07 '14 at 21:09

1 Answers1

0
return targetAngle + Math.Round((currentAngle - targetAngle)/(2*Math.Pi))*2*Math.Pi;
mbeckish
  • 10,485
  • 5
  • 30
  • 55
  • @AlexeiLevenkov - Why? The problem is to compute the integer factor k such that targetAngle + k * 2 * pi is as close as possible to currentAngle. Math.Round is there because of the restriction that k be an integer - it has nothing to do with radians vs degrees, because k is unitless. – mbeckish May 07 '14 at 21:01