github.com/jingcheng-WU/gonum@v0.9.1-0.20210323123734-f1a2a11a8f7b/stat/distmat/unit_vector_test.go (about)

     1  // Copyright ©2020 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 distmat
     6  
     7  import (
     8  	"testing"
     9  
    10  	"golang.org/x/exp/rand"
    11  
    12  	"github.com/jingcheng-WU/gonum/floats/scalar"
    13  	"github.com/jingcheng-WU/gonum/mat"
    14  )
    15  
    16  func TestUnitVector(t *testing.T) {
    17  	u := NewUnitVector(rand.NewSource(1))
    18  	for _, d := range []int{10, 32, 64, 100} {
    19  		v := mat.NewVecDense(d, nil)
    20  		u.UnitVecTo(v)
    21  		l := mat.Norm(v, 2)
    22  		if !scalar.EqualWithinAbs(l, 1.0, 1e-12) {
    23  			t.Errorf("expected length 1 but got %f", l)
    24  		}
    25  	}
    26  }
    27  
    28  func TestUnitVectorStats(t *testing.T) {
    29  	n := 1e7
    30  	u := NewUnitVector(rand.NewSource(1))
    31  	for _, d := range []int{1, 2, 3} {
    32  		v := mat.NewVecDense(d, nil)
    33  		tot := mat.NewVecDense(d, nil)
    34  		for i := 0; i < int(n); i++ {
    35  			u.UnitVecTo(v)
    36  			tot.AddVec(tot, v)
    37  		}
    38  		tot.ScaleVec(1/n, tot)
    39  		// Each dimension should average out to 0.
    40  		for i := 0; i < d; i++ {
    41  			if !scalar.EqualWithinAbs(tot.AtVec(i), 0.0, 1e-3) {
    42  				t.Errorf("expected average entry 0 but got %f", tot.AtVec(i))
    43  			}
    44  		}
    45  		l := mat.Norm(tot, 2)
    46  		// And the length should be 0.
    47  		if !scalar.EqualWithinAbs(l, 0.0, 1e-3) {
    48  			t.Errorf("expected length 0 but got %f", l)
    49  		}
    50  	}
    51  }