8

I've got this code snippet, and I'm wondering why the results of the first method differ from the results of the second method, given the same input?

public double AngleBetween_1(vector a, vector b) {
  var dotProd = a.Dot(b);
  var lenProd = a.Len*b.Len;
  var divOperation = dotProd/lenProd;
  return Math.Acos(divOperation) * (180.0 / Math.PI);
}

public double AngleBetween_2(vector a, vector b) {
  var dotProd = a.Dot(b);
  var lenProd = a.Len*b.Len;
  var divOperation = dotProd/lenProd;
  return (1/Math.Cos(divOperation)) * (180.0 / Math.PI);
}
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
bitcycle
  • 7,632
  • 16
  • 70
  • 121

3 Answers3

16

It's because the first method is correct, while the second method is incorrect.

You may notice that the arccosine function is sometimes written "acos" and sometimes written "cos-1". This is a quirk of mathematical notation: "cos-1" is really the arccosine and NOT the reciprocal of the cosine (which is the secant).

However, if you ever see "cos2", then that's the square of the cosine, and "cos3" is the cube of the cosine. The notation for trigonometric functions is weird this way. Most operators use superscripts to indicate repeated application.

Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415
5

Math.Acos(divOperation) isn't equivalent to 1/Math.Cos(divOperation). arccos is the inverse function of cos, not the multiplicative inverse.

kevingessner
  • 18,559
  • 5
  • 43
  • 63
3

Probably because acos(x) ≠ 1/cos(x).

slacker
  • 2,142
  • 11
  • 10