1package ewma 2 3// Copyright (c) 2013 VividCortex, Inc. All rights reserved. 4// Please see the LICENSE file for applicable license terms. 5 6import ( 7 "math" 8 "testing" 9) 10 11const testMargin = 0.00000001 12 13var samples = [100]float64{ 14 4599, 5711, 4746, 4621, 5037, 4218, 4925, 4281, 5207, 5203, 5594, 5149, 15 4948, 4994, 6056, 4417, 4973, 4714, 4964, 5280, 5074, 4913, 4119, 4522, 16 4631, 4341, 4909, 4750, 4663, 5167, 3683, 4964, 5151, 4892, 4171, 5097, 17 3546, 4144, 4551, 6557, 4234, 5026, 5220, 4144, 5547, 4747, 4732, 5327, 18 5442, 4176, 4907, 3570, 4684, 4161, 5206, 4952, 4317, 4819, 4668, 4603, 19 4885, 4645, 4401, 4362, 5035, 3954, 4738, 4545, 5433, 6326, 5927, 4983, 20 5364, 4598, 5071, 5231, 5250, 4621, 4269, 3953, 3308, 3623, 5264, 5322, 21 5395, 4753, 4936, 5315, 5243, 5060, 4989, 4921, 4480, 3426, 3687, 4220, 22 3197, 5139, 6101, 5279, 23} 24 25func withinMargin(a, b float64) bool { 26 return math.Abs(a-b) <= testMargin 27} 28 29func TestSimpleEWMA(t *testing.T) { 30 var e SimpleEWMA 31 for _, f := range samples { 32 e.Add(f) 33 } 34 if !withinMargin(e.Value(), 4734.500946466118) { 35 t.Errorf("e.Value() is %v, wanted %v", e.Value(), 4734.500946466118) 36 } 37 e.Set(1.0) 38 if e.Value() != 1.0 { 39 t.Errorf("e.Value() is %d", e.Value()) 40 } 41} 42 43func TestVariableEWMA(t *testing.T) { 44 e := NewMovingAverage(30) 45 for _, f := range samples { 46 e.Add(f) 47 } 48 if !withinMargin(e.Value(), 4734.500946466118) { 49 t.Errorf("e.Value() is %v, wanted %v", e.Value(), 4734.500946466118) 50 } 51 e.Set(1.0) 52 if e.Value() != 1.0 { 53 t.Errorf("e.Value() is %d", e.Value()) 54 } 55} 56 57func TestVariableEWMA2(t *testing.T) { 58 e := NewMovingAverage(5) 59 for _, f := range samples { 60 e.Add(f) 61 } 62 if !withinMargin(e.Value(), 5015.397367486725) { 63 t.Errorf("e.Value() is %v, wanted %v", e.Value(), 5015.397367486725) 64 } 65} 66 67func TestVariableEWMAWarmup(t *testing.T) { 68 e := NewMovingAverage(5) 69 for i, f := range samples { 70 e.Add(f) 71 72 // all values returned during warmup should be 0.0 73 if uint8(i) < WARMUP_SAMPLES { 74 if e.Value() != 0.0 { 75 t.Errorf("e.Value() is %v, expected %v", e.Value(), 0.0) 76 } 77 } 78 } 79 e = NewMovingAverage(5) 80 e.Set(5) 81 e.Add(1) 82 if e.Value() >= 5 { 83 t.Errorf("e.Value() is %d, expected it to decay towards 0", e.Value()) 84 } 85} 86 87func TestVariableEWMAWarmup2(t *testing.T) { 88 e := NewMovingAverage(5) 89 testSamples := [12]float64{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 10000, 1} 90 for i, f := range testSamples { 91 e.Add(f) 92 93 // all values returned during warmup should be 0.0 94 if uint8(i) < WARMUP_SAMPLES { 95 if e.Value() != 0.0 { 96 t.Errorf("e.Value() is %v, expected %v", e.Value(), 0.0) 97 } 98 } 99 } 100 if val := e.Value(); val == 1.0 { 101 t.Errorf("e.Value() is expected to be greater than %v", 1.0) 102 } 103} 104