ldexp.go 871 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package math32
  2. // Ldexp is the inverse of Frexp.
  3. // It returns frac × 2**exp.
  4. //
  5. // Special cases are:
  6. // Ldexp(±0, exp) = ±0
  7. // Ldexp(±Inf, exp) = ±Inf
  8. // Ldexp(NaN, exp) = NaN
  9. func Ldexp(frac float32, exp int) float32 {
  10. return ldexp(frac, exp)
  11. }
  12. func ldexp(frac float32, exp int) float32 {
  13. // special cases
  14. switch {
  15. case frac == 0:
  16. return frac // correctly return -0
  17. case IsInf(frac, 0) || IsNaN(frac):
  18. return frac
  19. }
  20. frac, e := normalize(frac)
  21. exp += e
  22. x := Float32bits(frac)
  23. exp += int(x>>shift)&mask - bias
  24. if exp < -149 {
  25. return Copysign(0, frac) // underflow
  26. }
  27. if exp > 127 { // overflow
  28. if frac < 0 {
  29. return Inf(-1)
  30. }
  31. return Inf(1)
  32. }
  33. var m float32 = 1
  34. if exp < -(127 - 1) { // denormal
  35. exp += shift
  36. m = 1.0 / (1 << 23) // 1/(2**-23)
  37. }
  38. x &^= mask << shift
  39. x |= uint32(exp+bias) << shift
  40. return m * Float32frombits(x)
  41. }