dim.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. // Dim returns the maximum of x-y or 0.
  6. //
  7. // Special cases are:
  8. // Dim(+Inf, +Inf) = NaN
  9. // Dim(-Inf, -Inf) = NaN
  10. // Dim(x, NaN) = Dim(NaN, x) = NaN
  11. func Dim(x, y float64) float64 {
  12. return dim(x, y)
  13. }
  14. func dim(x, y float64) float64 {
  15. return max(x-y, 0)
  16. }
  17. // Max returns the larger of x or y.
  18. //
  19. // Special cases are:
  20. // Max(x, +Inf) = Max(+Inf, x) = +Inf
  21. // Max(x, NaN) = Max(NaN, x) = NaN
  22. // Max(+0, ±0) = Max(±0, +0) = +0
  23. // Max(-0, -0) = -0
  24. func Max(x, y float64) float64 {
  25. return max(x, y)
  26. }
  27. func max(x, y float64) float64 {
  28. // special cases
  29. switch {
  30. case IsInf(x, 1) || IsInf(y, 1):
  31. return Inf(1)
  32. case IsNaN(x) || IsNaN(y):
  33. return NaN()
  34. case x == 0 && x == y:
  35. if Signbit(x) {
  36. return y
  37. }
  38. return x
  39. }
  40. if x > y {
  41. return x
  42. }
  43. return y
  44. }
  45. // Min returns the smaller of x or y.
  46. //
  47. // Special cases are:
  48. // Min(x, -Inf) = Min(-Inf, x) = -Inf
  49. // Min(x, NaN) = Min(NaN, x) = NaN
  50. // Min(-0, ±0) = Min(±0, -0) = -0
  51. func Min(x, y float64) float64 {
  52. return min(x, y)
  53. }
  54. func min(x, y float64) float64 {
  55. // special cases
  56. switch {
  57. case IsInf(x, -1) || IsInf(y, -1):
  58. return Inf(-1)
  59. case IsNaN(x) || IsNaN(y):
  60. return NaN()
  61. case x == 0 && x == y:
  62. if Signbit(x) {
  63. return x
  64. }
  65. return y
  66. }
  67. if x < y {
  68. return x
  69. }
  70. return y
  71. }