github.com/primecitizens/pcz/std@v0.2.1/math/dim.go (about)

     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  
     5  package math
     6  
     7  // Dim returns the maximum of x-y or 0.
     8  //
     9  // Special cases are:
    10  //
    11  //	Dim(+Inf, +Inf) = NaN
    12  //	Dim(-Inf, -Inf) = NaN
    13  //	Dim(x, NaN) = Dim(NaN, x) = NaN
    14  func Dim(x, y float64) float64 {
    15  	// The special cases result in NaN after the subtraction:
    16  	//      +Inf - +Inf = NaN
    17  	//      -Inf - -Inf = NaN
    18  	//       NaN - y    = NaN
    19  	//         x - NaN  = NaN
    20  	v := x - y
    21  	if v <= 0 {
    22  		// v is negative or 0
    23  		return 0
    24  	}
    25  	// v is positive or NaN
    26  	return v
    27  }
    28  
    29  // Max returns the larger of x or y.
    30  //
    31  // Special cases are:
    32  //
    33  //	Max(x, +Inf) = Max(+Inf, x) = +Inf
    34  //	Max(x, NaN) = Max(NaN, x) = NaN
    35  //	Max(+0, ±0) = Max(±0, +0) = +0
    36  //	Max(-0, -0) = -0
    37  func Max(x, y float64) float64 {
    38  	return max(x, y)
    39  }
    40  
    41  func max(x, y float64) float64 {
    42  	// special cases
    43  	switch {
    44  	case IsInf(x, 1) || IsInf(y, 1):
    45  		return Inf(1)
    46  	case IsNaN(x) || IsNaN(y):
    47  		return NaN()
    48  	case x == 0 && x == y:
    49  		if Signbit(x) {
    50  			return y
    51  		}
    52  		return x
    53  	}
    54  	if x > y {
    55  		return x
    56  	}
    57  	return y
    58  }
    59  
    60  // Min returns the smaller of x or y.
    61  //
    62  // Special cases are:
    63  //
    64  //	Min(x, -Inf) = Min(-Inf, x) = -Inf
    65  //	Min(x, NaN) = Min(NaN, x) = NaN
    66  //	Min(-0, ±0) = Min(±0, -0) = -0
    67  func Min(x, y float64) float64 {
    68  	return min(x, y)
    69  }
    70  
    71  func min(x, y float64) float64 {
    72  	// special cases
    73  	switch {
    74  	case IsInf(x, -1) || IsInf(y, -1):
    75  		return Inf(-1)
    76  	case IsNaN(x) || IsNaN(y):
    77  		return NaN()
    78  	case x == 0 && x == y:
    79  		if Signbit(x) {
    80  			return x
    81  		}
    82  		return y
    83  	}
    84  	if x < y {
    85  		return x
    86  	}
    87  	return y
    88  }