From b6d505480a937276d92d5da766aa70e15008ce2d Mon Sep 17 00:00:00 2001 From: Ryan Ascheman Date: Wed, 30 Oct 2019 15:39:27 -0700 Subject: [PATCH] add count function --- tdigest.go | 9 +++++++++ tdigest_test.go | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/tdigest.go b/tdigest.go index e282f08..3de1c89 100644 --- a/tdigest.go +++ b/tdigest.go @@ -132,6 +132,15 @@ func (t *TDigest) Centroids() CentroidList { return cl } +func (t *TDigest) Count() float64 { + t.process() + count := 0.0 + for _, centroid := range t.processed { + count += centroid.Weight + } + return count +} + func (t *TDigest) updateCumulative() { if n := t.processed.Len() + 1; n <= cap(t.cumulative) { t.cumulative = t.cumulative[:n] diff --git a/tdigest_test.go b/tdigest_test.go index 2d9b22f..2c7522e 100644 --- a/tdigest_test.go +++ b/tdigest_test.go @@ -47,6 +47,43 @@ func init() { } } + +func TestTdigest_Count(t *testing.T) { + tests := []struct { + name string + data []float64 + digest *tdigest.TDigest + want float64 + }{ + { + name: "empty", + data: []float64{}, + want: 0, + }, + { + name: "not empty", + data: []float64{5, 4}, + want: 2, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + td := tt.digest + if td == nil { + td = tdigest.NewWithCompression(1000) + for _, x := range tt.data { + td.Add(x, 1) + } + } + got := td.Count() + if got != tt.want { + t.Errorf("unexpected count, got %g want %g", got, tt.want) + } + }) + } +} + func TestTdigest_Quantile(t *testing.T) { tests := []struct { name string