nextafter.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. // Nextafter32 returns the next representable float32 value after x towards y.
  6. // Special cases:
  7. // Nextafter32(x, x) = x
  8. // Nextafter32(NaN, y) = NaN
  9. // Nextafter32(x, NaN) = NaN
  10. func Nextafter32(x, y float32) (r float32) {
  11. switch {
  12. case IsNaN(float64(x)) || IsNaN(float64(y)): // special case
  13. r = float32(NaN())
  14. case x == y:
  15. r = x
  16. case x == 0:
  17. r = float32(Copysign(float64(Float32frombits(1)), float64(y)))
  18. case (y > x) == (x > 0):
  19. r = Float32frombits(Float32bits(x) + 1)
  20. default:
  21. r = Float32frombits(Float32bits(x) - 1)
  22. }
  23. return
  24. }
  25. // Nextafter returns the next representable float64 value after x towards y.
  26. // Special cases:
  27. // Nextafter64(x, x) = x
  28. // Nextafter64(NaN, y) = NaN
  29. // Nextafter64(x, NaN) = NaN
  30. func Nextafter(x, y float64) (r float64) {
  31. switch {
  32. case IsNaN(x) || IsNaN(y): // special case
  33. r = NaN()
  34. case x == y:
  35. r = x
  36. case x == 0:
  37. r = Copysign(Float64frombits(1), y)
  38. case (y > x) == (x > 0):
  39. r = Float64frombits(Float64bits(x) + 1)
  40. default:
  41. r = Float64frombits(Float64bits(x) - 1)
  42. }
  43. return
  44. }