Source file src/math/dim.go

     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  //
    38  // Note that this differs from the built-in function max when called
    39  // with NaN and +Inf.
    40  func Max(x, y float64) float64 {
    41  	if haveArchMax {
    42  		return archMax(x, y)
    43  	}
    44  	return max(x, y)
    45  }
    46  
    47  func max(x, y float64) float64 {
    48  	// special cases
    49  	switch {
    50  	case IsInf(x, 1) || IsInf(y, 1):
    51  		return Inf(1)
    52  	case IsNaN(x) || IsNaN(y):
    53  		return NaN()
    54  	case x == 0 && x == y:
    55  		if Signbit(x) {
    56  			return y
    57  		}
    58  		return x
    59  	}
    60  	if x > y {
    61  		return x
    62  	}
    63  	return y
    64  }
    65  
    66  // Min returns the smaller of x or y.
    67  //
    68  // Special cases are:
    69  //
    70  //	Min(x, -Inf) = Min(-Inf, x) = -Inf
    71  //	Min(x, NaN) = Min(NaN, x) = NaN
    72  //	Min(-0, ±0) = Min(±0, -0) = -0
    73  //
    74  // Note that this differs from the built-in function min when called
    75  // with NaN and -Inf.
    76  func Min(x, y float64) float64 {
    77  	if haveArchMin {
    78  		return archMin(x, y)
    79  	}
    80  	return min(x, y)
    81  }
    82  
    83  func min(x, y float64) float64 {
    84  	// special cases
    85  	switch {
    86  	case IsInf(x, -1) || IsInf(y, -1):
    87  		return Inf(-1)
    88  	case IsNaN(x) || IsNaN(y):
    89  		return NaN()
    90  	case x == 0 && x == y:
    91  		if Signbit(x) {
    92  			return x
    93  		}
    94  		return y
    95  	}
    96  	if x < y {
    97  		return x
    98  	}
    99  	return y
   100  }
   101  

View as plain text