gonum.org/v1/gonum@v0.14.0/stat/distmat/unit_vector_example_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_test 6 7 import ( 8 "fmt" 9 10 "golang.org/x/exp/rand" 11 12 "gonum.org/v1/gonum/mat" 13 "gonum.org/v1/gonum/stat/distmat" 14 ) 15 16 // ExampleUnitVector uses the UnitVector distribution to take 17 // a random walk in n-space. At the end it computes how far 18 // from the origin the walk finished. 19 func ExampleUnitVector() { 20 src := rand.NewSource(1) 21 rnd := rand.New(src) 22 dist := distmat.NewUnitVector(src) 23 24 // Draw a random dimension for the space to walk through. 25 nDim := 1 + rnd.Intn(100) 26 // Vectors to hold the current position and next step. 27 position := mat.NewVecDense(nDim, nil) 28 step := mat.NewVecDense(nDim, nil) 29 30 // Draw a random number of steps to take. 31 nSteps := 1 + rnd.Intn(100) 32 for i := 0; i < nSteps; i++ { 33 // Draw a random step and update the position. 34 dist.UnitVecTo(step) 35 position.AddVec(position, step) 36 } 37 38 // Finally compute distance from the origin. 39 distance := mat.Norm(position, 2) 40 fmt.Printf("took %d steps in %d-space, walked %1.1f in total", nSteps, nDim, distance) 41 // Output: 42 // took 22 steps in 52-space, walked 5.3 in total 43 }