modf.go 796 B

12345678910111213141516171819202122232425262728293031323334353637
  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. // Modf returns integer and fractional floating-point numbers
  6. // that sum to f. Both values have the same sign as f.
  7. //
  8. // Special cases are:
  9. // Modf(±Inf) = ±Inf, NaN
  10. // Modf(NaN) = NaN, NaN
  11. func Modf(f float64) (int float64, frac float64) {
  12. return modf(f)
  13. }
  14. func modf(f float64) (int float64, frac float64) {
  15. if f < 1 {
  16. if f < 0 {
  17. int, frac = Modf(-f)
  18. return -int, -frac
  19. }
  20. return 0, f
  21. }
  22. x := Float64bits(f)
  23. e := uint(x>>shift)&mask - bias
  24. // Keep the top 12+e bits, the integer part; clear the rest.
  25. if e < 64-12 {
  26. x &^= 1<<(64-12-e) - 1
  27. }
  28. int = Float64frombits(x)
  29. frac = f - int
  30. return
  31. }