atan2.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package math32
  2. // Atan2 returns the arc tangent of y/x, using the signs of the two to determine the quadrant of the return value.
  3. // Special cases are (in order):
  4. // Atan2(y, NaN) = NaN
  5. // Atan2(NaN, x) = NaN
  6. // Atan2(+0, x>=0) = +0
  7. // Atan2(-0, x>=0) = -0
  8. // Atan2(+0, x<=-0) = +Pi
  9. // Atan2(-0, x<=-0) = -Pi
  10. // Atan2(y>0, 0) = +Pi/2
  11. // Atan2(y<0, 0) = -Pi/2
  12. // Atan2(+Inf, +Inf) = +Pi/4
  13. // Atan2(-Inf, +Inf) = -Pi/4
  14. // Atan2(+Inf, -Inf) = 3Pi/4
  15. // Atan2(-Inf, -Inf) = -3Pi/4
  16. // Atan2(y, +Inf) = 0
  17. // Atan2(y>0, -Inf) = +Pi
  18. // Atan2(y<0, -Inf) = -Pi
  19. // Atan2(+Inf, x) = +Pi/2
  20. // Atan2(-Inf, x) = -Pi/2
  21. func Atan2(y, x float32) float32 {
  22. // special cases
  23. switch {
  24. case IsNaN(y) || IsNaN(x):
  25. return NaN()
  26. case y == 0:
  27. if x >= 0 && !Signbit(x) {
  28. return Copysign(0, y)
  29. }
  30. return Copysign(Pi, y)
  31. case x == 0:
  32. return Copysign(Pi/2, y)
  33. case IsInf(x, 0):
  34. if IsInf(x, 1) {
  35. switch {
  36. case IsInf(y, 0):
  37. return Copysign(Pi/4, y)
  38. default:
  39. return Copysign(0, y)
  40. }
  41. }
  42. switch {
  43. case IsInf(y, 0):
  44. return Copysign(3*Pi/4, y)
  45. default:
  46. return Copysign(Pi, y)
  47. }
  48. case IsInf(y, 0):
  49. return Copysign(Pi/2, y)
  50. }
  51. // Call atan and determine the quadrant.
  52. q := Atan(y / x)
  53. if x < 0 {
  54. if q <= 0 {
  55. return q + Pi
  56. }
  57. return q - Pi
  58. }
  59. return q
  60. }