logb.go 1014 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. // Logb returns the binary exponent of x.
  6. //
  7. // Special cases are:
  8. // Logb(±Inf) = +Inf
  9. // Logb(0) = -Inf
  10. // Logb(NaN) = NaN
  11. func Logb(x float64) float64 {
  12. // special cases
  13. switch {
  14. case x == 0:
  15. return Inf(-1)
  16. case IsInf(x, 0):
  17. return Inf(1)
  18. case IsNaN(x):
  19. return x
  20. }
  21. return float64(ilogb(x))
  22. }
  23. // Ilogb returns the binary exponent of x as an integer.
  24. //
  25. // Special cases are:
  26. // Ilogb(±Inf) = MaxInt32
  27. // Ilogb(0) = MinInt32
  28. // Ilogb(NaN) = MaxInt32
  29. func Ilogb(x float64) int {
  30. // special cases
  31. switch {
  32. case x == 0:
  33. return MinInt32
  34. case IsNaN(x):
  35. return MaxInt32
  36. case IsInf(x, 0):
  37. return MaxInt32
  38. }
  39. return ilogb(x)
  40. }
  41. // logb returns the binary exponent of x. It assumes x is finite and
  42. // non-zero.
  43. func ilogb(x float64) int {
  44. x, exp := normalize(x)
  45. return int((Float64bits(x)>>shift)&mask) - bias + exp
  46. }