ldexp.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. // Ldexp is the inverse of Frexp.
  6. // It returns frac × 2**exp.
  7. //
  8. // Special cases are:
  9. // Ldexp(±0, exp) = ±0
  10. // Ldexp(±Inf, exp) = ±Inf
  11. // Ldexp(NaN, exp) = NaN
  12. //extern ldexp
  13. func libc_ldexp(float64, int) float64
  14. func Ldexp(frac float64, exp int) float64 {
  15. r := libc_ldexp(frac, exp)
  16. return r
  17. }
  18. func ldexp(frac float64, exp int) float64 {
  19. // special cases
  20. switch {
  21. case frac == 0:
  22. return frac // correctly return -0
  23. case IsInf(frac, 0) || IsNaN(frac):
  24. return frac
  25. }
  26. frac, e := normalize(frac)
  27. exp += e
  28. x := Float64bits(frac)
  29. exp += int(x>>shift)&mask - bias
  30. if exp < -1074 {
  31. return Copysign(0, frac) // underflow
  32. }
  33. if exp > 1023 { // overflow
  34. if frac < 0 {
  35. return Inf(-1)
  36. }
  37. return Inf(1)
  38. }
  39. var m float64 = 1
  40. if exp < -1022 { // denormal
  41. exp += 52
  42. m = 1.0 / (1 << 52) // 2**-52
  43. }
  44. x &^= mask << shift
  45. x |= uint64(exp+bias) << shift
  46. return m * Float64frombits(x)
  47. }