floor.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright 2009-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. // Floor returns the greatest integer value less than or equal to x.
  6. //
  7. // Special cases are:
  8. // Floor(±0) = ±0
  9. // Floor(±Inf) = ±Inf
  10. // Floor(NaN) = NaN
  11. //extern floor
  12. func libc_floor(float64) float64
  13. func Floor(x float64) float64 {
  14. return libc_floor(x)
  15. }
  16. func floor(x float64) float64 {
  17. if x == 0 || IsNaN(x) || IsInf(x, 0) {
  18. return x
  19. }
  20. if x < 0 {
  21. d, fract := Modf(-x)
  22. if fract != 0.0 {
  23. d = d + 1
  24. }
  25. return -d
  26. }
  27. d, _ := Modf(x)
  28. return d
  29. }
  30. // Ceil returns the least integer value greater than or equal to x.
  31. //
  32. // Special cases are:
  33. // Ceil(±0) = ±0
  34. // Ceil(±Inf) = ±Inf
  35. // Ceil(NaN) = NaN
  36. //extern ceil
  37. func libc_ceil(float64) float64
  38. func Ceil(x float64) float64 {
  39. return libc_ceil(x)
  40. }
  41. func ceil(x float64) float64 {
  42. return -Floor(-x)
  43. }
  44. // Trunc returns the integer value of x.
  45. //
  46. // Special cases are:
  47. // Trunc(±0) = ±0
  48. // Trunc(±Inf) = ±Inf
  49. // Trunc(NaN) = NaN
  50. func Trunc(x float64) float64 {
  51. return trunc(x)
  52. }
  53. func trunc(x float64) float64 {
  54. if x == 0 || IsNaN(x) || IsInf(x, 0) {
  55. return x
  56. }
  57. d, _ := Modf(x)
  58. return d
  59. }