github.com/searKing/golang/go@v1.2.117/exp/math/dim.go (about) 1 // Copyright 2022 The searKing Author. 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 import ( 8 "cmp" 9 "math" 10 11 constraints_ "github.com/searKing/golang/go/exp/constraints" 12 "golang.org/x/exp/constraints" 13 ) 14 15 // Dim returns the maximum of x-y or 0. 16 func Dim[T constraints_.Number](x, y T) T { 17 v := x - y 18 if v <= 0 { 19 // v is negative or 0 20 return 0 21 } 22 // v is positive or NaN 23 return v 24 } 25 26 // Max returns the largest of s. 27 // Deprecated: Use [max] built-in instead since go1.21. 28 func Max[T cmp.Ordered](s ...T) T { 29 if len(s) == 0 { 30 var zero T 31 return zero 32 } 33 m := s[0] 34 for _, v := range s[1:] { 35 if m < v { 36 m = v 37 } 38 } 39 return m 40 } 41 42 // Min returns the smallest of s. 43 // Deprecated: Use [min] built-in instead since go1.21. 44 func Min[T cmp.Ordered](s ...T) T { 45 if len(s) == 0 { 46 var zero T 47 return zero 48 } 49 m := s[0] 50 for _, v := range s[1:] { 51 if m > v { 52 m = v 53 } 54 } 55 return m 56 } 57 58 // Clamp returns the value between boundary [lo,hi], as v < lo ? v : hi > v : hi : v. 59 // Reference to lo if v is less than lo, reference to hi if hi is less than v, otherwise reference to v. 60 // If v compares equivalent to either bound, returns a reference to v, not the bound. 61 func Clamp[T cmp.Ordered](v, lo, hi T) T { 62 if lo > hi { 63 lo, hi = hi, lo 64 } 65 if v < lo { 66 return lo 67 } 68 if hi < v { 69 return hi 70 } 71 return v 72 } 73 74 // Sum returns the sum of s. 75 func Sum[T, R constraints_.Number](s ...T) R { 76 if len(s) == 0 { 77 var zero R 78 return zero 79 } 80 m := R(s[0]) 81 for _, v := range s[1:] { 82 m += R(v) 83 } 84 return m 85 } 86 87 // Mean returns the mean of s. 88 func Mean[T constraints_.Number, R constraints.Float](s ...T) R { 89 if len(s) == 0 { 90 var zero R 91 return zero 92 } 93 return Sum[T, R](s...) / R(len(s)) 94 } 95 96 // Variance returns the variance of s. 97 func Variance[T constraints_.Number, R constraints.Float](s ...T) R { 98 if len(s) == 0 || len(s) == 1 { 99 var zero R 100 return zero 101 } 102 m := Mean[T, R](s...) 103 104 var res R 105 for _, v := range s { 106 d := R(v) - m 107 res += d * d 108 } 109 110 return res / R(len(s)-1) 111 } 112 113 // StandardDeviation returns the standard deviation of s. 114 func StandardDeviation[T constraints_.Number, R constraints.Float](s ...T) R { 115 if len(s) == 0 || len(s) == 1 { 116 var zero R 117 return zero 118 } 119 return R(math.Sqrt(Variance[T, float64](s...))) 120 }