github.com/yaricom/goNEAT@v0.0.0-20210507221059-e2110b885482/experiments/floats.go (about)

     1  package experiments
     2  
     3  import (
     4  	"sort"
     5  	"math"
     6  )
     7  
     8  // Floats provides descriptive statistics on a slice of float64 values
     9  type Floats []float64
    10  
    11  // Min returns the smallest value in the slice
    12  func (x Floats) Min() float64 {
    13  	if len(x) == 0 {
    14  		return 0.0
    15  	}
    16  	sort.Float64s(x)
    17  	return x[0]
    18  }
    19  
    20  // Max returns the greatest value in the slice
    21  func (x Floats) Max() float64 {
    22  	if len(x) == 0 {
    23  		return 0.0
    24  	}
    25  	sort.Float64s(x)
    26  	return x[len(x)-1]
    27  }
    28  
    29  // Sum returns the total of the values in the slice
    30  func (x Floats) Sum() float64 {
    31  	s := 0.0
    32  	for _, v := range x {
    33  		s += v
    34  	}
    35  	return s
    36  }
    37  
    38  // Mean returns the average of the values in the slice
    39  func (x Floats) Mean() float64 {
    40  	if len(x) == 0 {
    41  		return 0.0
    42  	}
    43  	return x.Sum() / float64(len(x))
    44  }
    45  
    46  // Median returns the middle value in the slice
    47  func (x Floats) Median() float64 {
    48  	sort.Float64s(x)
    49  	n := len(x)
    50  	switch {
    51  	case n == 0:
    52  		return 0.0
    53  	case n%2 == 0:
    54  		return (x[n/2-1] + x[n/2]) / 2.0
    55  	default:
    56  		return x[n/2]
    57  	}
    58  }
    59  
    60  func (x Floats) Q25() float64 {
    61  	if len(x) == 0 {
    62  		return 0.0
    63  	}
    64  	sort.Float64s(x)
    65  	n := len(x) / 4
    66  	return x[n]
    67  }
    68  
    69  func (x Floats) Q75() float64 {
    70  	if len(x) == 0 {
    71  		return 0.0
    72  	}
    73  	sort.Float64s(x)
    74  	n := len(x) * 3 / 4
    75  	return x[n]
    76  }
    77  
    78  // Variance returns the variance of the values in the slice
    79  func (x Floats) Variance() float64 {
    80  	if len(x) == 0 {
    81  		return 0.0
    82  	}
    83  	m := x.Mean()
    84  	s := 0.0
    85  	for _, v := range x {
    86  		s += (v - m) * (v - m)
    87  	}
    88  	return s
    89  }
    90  
    91  // Stdev returns the standard deviation of the values in the slice
    92  func (x Floats) Stdev() float64 {
    93  	if len(x) == 0 {
    94  		return 0.0
    95  	}
    96  	v := x.Variance()
    97  	return math.Sqrt(v / float64(len(x)))
    98  }