github.com/gopherd/gonum@v0.0.4/stat/sampleuv/withoutreplacement_test.go (about) 1 // Copyright ©2017 The Gonum 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 sampleuv 6 7 import ( 8 "testing" 9 10 "math/rand" 11 12 "github.com/gopherd/gonum/floats" 13 ) 14 15 func TestWithoutReplacement(t *testing.T) { 16 for cas, test := range []struct { 17 N int 18 K int 19 Src *rand.Rand 20 Trials int 21 Tol float64 22 }{ 23 { 24 // Test with perm and source. 25 N: 10, K: 5, Src: rand.New(rand.NewSource(1)), 26 Trials: 100000, Tol: 1e-3, 27 }, 28 { 29 // Test without perm and with source. 30 N: 10, K: 3, Src: rand.New(rand.NewSource(1)), 31 Trials: 100000, Tol: 1e-3, 32 }, 33 } { 34 dist := make([]float64, test.N) 35 for trial := 0; trial < test.Trials; trial++ { 36 idxs := make([]int, test.K) 37 WithoutReplacement(idxs, test.N, test.Src) 38 39 allDiff := true 40 for i := 0; i < len(idxs); i++ { 41 v := idxs[i] 42 for j := i + 1; j < len(idxs); j++ { 43 if v == idxs[j] { 44 allDiff = false 45 break 46 } 47 } 48 } 49 if !allDiff { 50 t.Errorf("Cas %d: Repeat in sampling. Idxs =%v", cas, idxs) 51 } 52 for _, v := range idxs { 53 dist[v]++ 54 } 55 } 56 div := 1 / (float64(test.Trials) * float64(test.K)) 57 floats.Scale(div, dist) 58 want := make([]float64, test.N) 59 for i := range want { 60 want[i] = 1 / float64(test.N) 61 } 62 if !floats.EqualApprox(want, dist, test.Tol) { 63 t.Errorf("Cas %d: biased sampling. Want = %v, got = %v", cas, want, dist) 64 } 65 } 66 }