File: histogram_test.go

package info (click to toggle)
golang-github-vividcortex-gohistogram 1.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 172 kB
  • sloc: makefile: 2
file content (62 lines) | stat: -rw-r--r-- 1,781 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package gohistogram

// Copyright (c) 2013 VividCortex, Inc. All rights reserved.
// Please see the LICENSE file for applicable license terms.

import (
	"math"
	"testing"
)

func approx(x, y float64) bool {
	return math.Abs(x-y) < 0.2
}

func TestHistogram(t *testing.T) {
	h := NewHistogram(160)
	for _, val := range testData {
		h.Add(float64(val))
	}
	if h.Count() != 14999 {
		t.Errorf("Expected h.Count() to be 14999, got %v", h.Count())
	}

	if firstQ := h.Quantile(0.25); !approx(firstQ, 14) {
		t.Errorf("Expected 25th percentile to be %v, got %v", 14, firstQ)
	}
	if median := h.Quantile(0.5); !approx(median, 18) {
		t.Errorf("Expected 50th percentile to be %v, got %v", 18, median)
	}
	if thirdQ := h.Quantile(0.75); !approx(thirdQ, 22) {
		t.Errorf("Expected 75th percentile to be %v, got %v", 22, thirdQ)
	}
	if cdf := h.CDF(18); !approx(cdf, 0.5) {
		t.Errorf("Expected CDF(median) to be %v, got %v", 0.5, cdf)
	}
	if cdf := h.CDF(22); !approx(cdf, 0.75) {
		t.Errorf("Expected CDF(3rd quartile) to be %v, got %v", 0.75, cdf)
	}
}

func TestWeightedHistogram(t *testing.T) {
	h := NewWeightedHistogram(160, 1)
	for _, val := range testData {
		h.Add(float64(val))
	}

	if firstQ := h.Quantile(0.25); !approx(firstQ, 14) {
		t.Errorf("Expected 25th percentile to be %v, got %v", 14, firstQ)
	}
	if median := h.Quantile(0.5); !approx(median, 18) {
		t.Errorf("Expected 50th percentile to be %v, got %v", 18, median)
	}
	if thirdQ := h.Quantile(0.75); !approx(thirdQ, 22) {
		t.Errorf("Expected 75th percentile to be %v, got %v", 22, thirdQ)
	}
	if cdf := h.CDF(18); !approx(cdf, 0.5) {
		t.Errorf("Expected CDF(median) to be %v, got %v", 0.5, cdf)
	}
	if cdf := h.CDF(22); !approx(cdf, 0.75) {
		t.Errorf("Expected CDF(3rd quartile) to be %v, got %v", 0.75, cdf)
	}
}