gonum.org/v1/gonum@v0.14.0/stat/distuv/studentst_test.go (about) 1 // Copyright ©2016 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 distuv 6 7 import ( 8 "math" 9 "sort" 10 "testing" 11 12 "golang.org/x/exp/rand" 13 14 "gonum.org/v1/gonum/floats" 15 "gonum.org/v1/gonum/floats/scalar" 16 ) 17 18 func TestStudentsTProb(t *testing.T) { 19 t.Parallel() 20 for _, test := range []struct { 21 x, mu, sigma, nu, want float64 22 }{ 23 // Values comparison with scipy. 24 {0.01, 0, 1, 2.74, 0.364778548181318}, 25 {-0.01, 0, 1, 2.74, 0.364778548181318}, 26 {0.4, 0, 1, 1.6, 0.30376391362582678}, 27 {-0.4, 0, 1, 1.6, 0.30376391362582678}, 28 {0.2, 15, 5, 10, 0.0024440848858034393}, 29 } { 30 pdf := StudentsT{test.mu, test.sigma, test.nu, nil}.Prob(test.x) 31 if !scalar.EqualWithinAbsOrRel(pdf, test.want, 1e-10, 1e-10) { 32 t.Errorf("Pdf mismatch, x = %v, Nu = %v. Got %v, want %v", test.x, test.nu, pdf, test.want) 33 } 34 } 35 } 36 37 func TestStudentsT(t *testing.T) { 38 t.Parallel() 39 src := rand.New(rand.NewSource(1)) 40 for i, b := range []StudentsT{ 41 {0, 1, 3.3, src}, 42 {0, 1, 7.2, src}, 43 {0, 1, 12, src}, 44 {0.9, 0.8, 6, src}, 45 } { 46 testStudentsT(t, b, i) 47 } 48 } 49 50 func testStudentsT(t *testing.T, c StudentsT, i int) { 51 const ( 52 tol = 1e-2 53 n = 3e5 54 bins = 50 55 ) 56 x := make([]float64, n) 57 generateSamples(x, c) 58 sort.Float64s(x) 59 60 testRandLogProbContinuous(t, i, math.Inf(-1), x, c, tol, bins) 61 checkMean(t, i, x, c, tol) 62 if c.Nu > 2 { 63 checkVarAndStd(t, i, x, c, 5e-2) 64 } 65 checkProbContinuous(t, i, x, math.Inf(-1), math.Inf(1), c, 1e-10) 66 checkQuantileCDFSurvival(t, i, x, c, tol) 67 checkProbQuantContinuous(t, i, x, c, tol) 68 if c.Mu != c.Mode() { 69 t.Errorf("Mismatch in mode value: got %v, want %g", c.Mode(), c.Mu) 70 } 71 if c.NumParameters() != 3 { 72 t.Errorf("Mismatch in NumParameters: got %v, want 3", c.NumParameters()) 73 } 74 } 75 76 func TestStudentsTQuantile(t *testing.T) { 77 t.Parallel() 78 nSteps := 101 79 probs := make([]float64, nSteps) 80 floats.Span(probs, 0, 1) 81 for i, b := range []StudentsT{ 82 {0, 1, 3.3, nil}, 83 {0, 1, 7.2, nil}, 84 {0, 1, 12, nil}, 85 {0.9, 0.8, 6, nil}, 86 } { 87 for _, p := range probs { 88 x := b.Quantile(p) 89 p2 := b.CDF(x) 90 if !scalar.EqualWithinAbsOrRel(p, p2, 1e-10, 1e-10) { 91 t.Errorf("mismatch between CDF and Quantile. Case %v. Want %v, got %v", i, p, p2) 92 break 93 } 94 } 95 } 96 } 97 98 func TestStudentsVarianceSpecial(t *testing.T) { 99 t.Parallel() 100 dist := StudentsT{0, 1, 1, nil} 101 variance := dist.Variance() 102 if !math.IsNaN(variance) { 103 t.Errorf("Expected NaN variance for Nu <= 1, got %v", variance) 104 } 105 dist = StudentsT{0, 1, 2, nil} 106 variance = dist.Variance() 107 if !math.IsInf(variance, 1) { 108 t.Errorf("Expected +Inf variance for 1 < Nu <= 2, got %v", variance) 109 } 110 }