github.com/aclements/go-misc@v0.0.0-20240129233631-2f6ede80790c/benchplot/kza_test.go (about) 1 // Copyright 2015 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package main 6 7 import ( 8 "math/rand" 9 "testing" 10 ) 11 12 // Aeq returns true if expect and got are equal to 8 significant 13 // figures (1 part in 100 million). 14 func Aeq(expect, got float64) bool { 15 if expect < 0 && got < 0 { 16 expect, got = -expect, -got 17 } 18 return expect*0.99999999 <= got && got*0.99999999 <= expect 19 } 20 21 func TestMovingAverage(t *testing.T) { 22 // Test MovingAverage against the obvious (but slow) 23 // implementation. 24 xs := make([]float64, 100) 25 for iter := 0; iter < 10; iter++ { 26 for i := range xs { 27 xs[i] = rand.Float64() 28 } 29 m := 1 + 2*rand.Intn(100) 30 ys1, ys2 := MovingAverage(xs, m), slowMovingAverage(xs, m) 31 32 // TODO: Use stuff from mathtest. 33 for i, y1 := range ys1 { 34 if !Aeq(y1, ys2[i]) { 35 t.Fatalf("want %v, got %v", ys2, ys1) 36 } 37 } 38 } 39 } 40 41 func slowMovingAverage(xs []float64, m int) []float64 { 42 ys := make([]float64, len(xs)) 43 for i := range ys { 44 psum, n := 0.0, 0 45 for j := i - (m-1)/2; j <= i+(m-1)/2; j++ { 46 if 0 <= j && j < len(xs) { 47 psum += xs[j] 48 n++ 49 } 50 } 51 ys[i] = psum / float64(n) 52 } 53 return ys 54 }