Skip to content

Commit

Permalink
Merge fc8b32d into 6e25dc5
Browse files Browse the repository at this point in the history
  • Loading branch information
tzzed committed Apr 16, 2021
2 parents 6e25dc5 + fc8b32d commit e613d5e
Show file tree
Hide file tree
Showing 2 changed files with 87 additions and 0 deletions.
66 changes: 66 additions & 0 deletions data.go
@@ -1,5 +1,11 @@
package stats

import (
"fmt"
"sort"
"strconv"
)

// Float64Data is a named type for []float64 with helper methods
type Float64Data []float64

Expand Down Expand Up @@ -167,3 +173,63 @@ func (f Float64Data) Entropy() (float64, error) {
func (f Float64Data) Quartiles() (Quartiles, error) {
return Quartile(f)
}

func (f Float64Data) Count() int {
return len(f)
}

// Describe generate descriptive statistics. Return an error only if FloatData is empty.
func (f Float64Data) Describe(percentiles ...int) error {
mean, err := f.Mean()
if err != nil {
return err
}

// Indentation for readability.
const indent = 8

out := fmt.Sprintf("count %*s %d", indent-len("count"), "", f.Count())
fmt.Println(out)

out = fmt.Sprintf("mean %*s %f", indent-len("mean"), "", mean)
fmt.Println(out)

std, _ := f.StandardDeviation()
out = fmt.Sprintf("std %*s %f", indent-len("std"), "", std)
fmt.Println(out)

min, _ := f.Min()
out = fmt.Sprintf("min %*s %f", indent-len("min"), "", min)
fmt.Println(out)

// Percentiles.
mp := make(map[int]bool)
for _, p := range percentiles {
mp[p] = true
}

// check if defaults values are in the slice if not add them.
var pDefault = []int{25, 50, 75}
for _, d := range pDefault {
if _, ok := mp[d]; !ok {
percentiles = append(percentiles, d)
}
}
sort.Ints(percentiles)

for _, p := range percentiles {
v, _ := f.Percentile(float64(p))

out = fmt.Sprintf("%.d%% %*s %f", p, indent-len(strconv.FormatInt(int64(p), 10))-1, "", v)
fmt.Println(out)
}

max, _ := f.Max()
out = fmt.Sprintf("max %*s %f", indent-len("max"), "", max)
fmt.Println(out)

out = fmt.Sprintf("dtype %*s %T", indent-len("dtype"), "", f[0])
fmt.Println(out)

return nil
}
21 changes: 21 additions & 0 deletions data_test.go
@@ -1,6 +1,7 @@
package stats_test

import (
"errors"
"math"
"math/rand"
"reflect"
Expand Down Expand Up @@ -276,3 +277,23 @@ func TestQuartilesMethods(t *testing.T) {
t.Errorf("%s returned an error", getFunctionName(data1.Quartiles))
}
}

func TestDescribe(t *testing.T) {
df := stats.Float64Data{1, 2, 3, 4, 10, 80, 123, 83, 48, 30}
err := df.Describe()
if err != nil {
t.Errorf("%s returned an error", getFunctionName(data1.Quartiles))
}

err = df.Describe(1, 5, 10, 90)
if err != nil {
t.Errorf("%s returned an error", getFunctionName(data1.Quartiles))
}

df = stats.Float64Data{}
err = df.Describe()
if !errors.Is(err, stats.ErrEmptyInput) {
t.Errorf("error: %s ", err.Error())
}

}

0 comments on commit e613d5e

Please sign in to comment.