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