frexp.go 723 B

12345678910111213141516171819202122232425262728293031
  1. package math32
  2. // Frexp breaks f into a normalized fraction
  3. // and an integral power of two.
  4. // It returns frac and exp satisfying f == frac × 2**exp,
  5. // with the absolute value of frac in the interval [½, 1).
  6. //
  7. // Special cases are:
  8. // Frexp(±0) = ±0, 0
  9. // Frexp(±Inf) = ±Inf, 0
  10. // Frexp(NaN) = NaN, 0
  11. func Frexp(f float32) (frac float32, exp int) {
  12. return frexp(f)
  13. }
  14. func frexp(f float32) (frac float32, exp int) {
  15. // special cases
  16. switch {
  17. case f == 0:
  18. return f, 0 // correctly return -0
  19. case IsInf(f, 0) || IsNaN(f):
  20. return f, 0
  21. }
  22. f, exp = normalize(f)
  23. x := Float32bits(f)
  24. exp += int((x>>shift)&mask) - bias + 1
  25. x &^= mask << shift
  26. x |= (-1 + bias) << shift
  27. frac = Float32frombits(x)
  28. return
  29. }