atan2.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package math
  5. // Atan2 returns the arc tangent of y/x, using
  6. // the signs of the two to determine the quadrant
  7. // of the return value.
  8. //
  9. // Special cases are (in order):
  10. // Atan2(y, NaN) = NaN
  11. // Atan2(NaN, x) = NaN
  12. // Atan2(+0, x>=0) = +0
  13. // Atan2(-0, x>=0) = -0
  14. // Atan2(+0, x<=-0) = +Pi
  15. // Atan2(-0, x<=-0) = -Pi
  16. // Atan2(y>0, 0) = +Pi/2
  17. // Atan2(y<0, 0) = -Pi/2
  18. // Atan2(+Inf, +Inf) = +Pi/4
  19. // Atan2(-Inf, +Inf) = -Pi/4
  20. // Atan2(+Inf, -Inf) = 3Pi/4
  21. // Atan2(-Inf, -Inf) = -3Pi/4
  22. // Atan2(y, +Inf) = 0
  23. // Atan2(y>0, -Inf) = +Pi
  24. // Atan2(y<0, -Inf) = -Pi
  25. // Atan2(+Inf, x) = +Pi/2
  26. // Atan2(-Inf, x) = -Pi/2
  27. //extern atan2
  28. func libc_atan2(float64, float64) float64
  29. func Atan2(y, x float64) float64 {
  30. return libc_atan2(y, x)
  31. }
  32. func atan2(y, x float64) float64 {
  33. // special cases
  34. switch {
  35. case IsNaN(y) || IsNaN(x):
  36. return NaN()
  37. case y == 0:
  38. if x >= 0 && !Signbit(x) {
  39. return Copysign(0, y)
  40. }
  41. return Copysign(Pi, y)
  42. case x == 0:
  43. return Copysign(Pi/2, y)
  44. case IsInf(x, 0):
  45. if IsInf(x, 1) {
  46. switch {
  47. case IsInf(y, 0):
  48. return Copysign(Pi/4, y)
  49. default:
  50. return Copysign(0, y)
  51. }
  52. }
  53. switch {
  54. case IsInf(y, 0):
  55. return Copysign(3*Pi/4, y)
  56. default:
  57. return Copysign(Pi, y)
  58. }
  59. case IsInf(y, 0):
  60. return Copysign(Pi/2, y)
  61. }
  62. // Call atan and determine the quadrant.
  63. q := Atan(y / x)
  64. if x < 0 {
  65. if q <= 0 {
  66. return q + Pi
  67. }
  68. return q - Pi
  69. }
  70. return q
  71. }