atanh.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // Copyright 2010 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. // The original C code, the long comment, and the constants
  6. // below are from FreeBSD's /usr/src/lib/msun/src/e_atanh.c
  7. // and came with this notice. The go code is a simplified
  8. // version of the original C.
  9. //
  10. // ====================================================
  11. // Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
  12. //
  13. // Developed at SunPro, a Sun Microsystems, Inc. business.
  14. // Permission to use, copy, modify, and distribute this
  15. // software is freely granted, provided that this notice
  16. // is preserved.
  17. // ====================================================
  18. //
  19. //
  20. // __ieee754_atanh(x)
  21. // Method :
  22. // 1. Reduce x to positive by atanh(-x) = -atanh(x)
  23. // 2. For x>=0.5
  24. // 1 2x x
  25. // atanh(x) = --- * log(1 + -------) = 0.5 * log1p(2 * --------)
  26. // 2 1 - x 1 - x
  27. //
  28. // For x<0.5
  29. // atanh(x) = 0.5*log1p(2x+2x*x/(1-x))
  30. //
  31. // Special cases:
  32. // atanh(x) is NaN if |x| > 1 with signal;
  33. // atanh(NaN) is that NaN with no signal;
  34. // atanh(+-1) is +-INF with signal.
  35. //
  36. // Atanh returns the inverse hyperbolic tangent of x.
  37. //
  38. // Special cases are:
  39. // Atanh(1) = +Inf
  40. // Atanh(±0) = ±0
  41. // Atanh(-1) = -Inf
  42. // Atanh(x) = NaN if x < -1 or x > 1
  43. // Atanh(NaN) = NaN
  44. func Atanh(x float64) float64 {
  45. return libc_atanh(x)
  46. }
  47. //extern atanh
  48. func libc_atanh(float64) float64
  49. func atanh(x float64) float64 {
  50. const NearZero = 1.0 / (1 << 28) // 2**-28
  51. // special cases
  52. switch {
  53. case x < -1 || x > 1 || IsNaN(x):
  54. return NaN()
  55. case x == 1:
  56. return Inf(1)
  57. case x == -1:
  58. return Inf(-1)
  59. }
  60. sign := false
  61. if x < 0 {
  62. x = -x
  63. sign = true
  64. }
  65. var temp float64
  66. switch {
  67. case x < NearZero:
  68. temp = x
  69. case x < 0.5:
  70. temp = x + x
  71. temp = 0.5 * Log1p(temp+temp*x/(1-x))
  72. default:
  73. temp = 0.5 * Log1p((x+x)/(1-x))
  74. }
  75. if sign {
  76. temp = -temp
  77. }
  78. return temp
  79. }