github.com/xushiwei/go@v0.0.0-20130601165731-2b9d83f45bc9/src/pkg/math/rand/example_test.go (about) 1 // Copyright 2012 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 rand_test 6 7 import ( 8 "fmt" 9 "math/rand" 10 "os" 11 "text/tabwriter" 12 ) 13 14 // This test serves as an example but also makes sure we don't change 15 // the output of the random number generator when given a fixed seed. 16 17 // This example shows the use of each of the methods on a *Rand. 18 // The use of the global functions is the same, without the receiver. 19 func Example() { 20 // Create and seed the generator. 21 // Typically a non-fixed seed should be used, such as time.Now().UnixNano(). 22 // Using a fixed seed will produce the same output on every run. 23 r := rand.New(rand.NewSource(99)) 24 25 // The tabwriter here helps us generate aligned output. 26 w := tabwriter.NewWriter(os.Stdout, 1, 1, 1, ' ', 0) 27 defer w.Flush() 28 show := func(name string, v1, v2, v3 interface{}) { 29 fmt.Fprintf(w, "%s\t%v\t%v\t%v\n", name, v1, v2, v3) 30 } 31 32 // Float32 and Float64 values are in [0, 1). 33 show("Float32", r.Float32(), r.Float32(), r.Float32()) 34 show("Float64", r.Float64(), r.Float64(), r.Float64()) 35 36 // ExpFloat64 values have an average of 1 but decay exponentially. 37 show("ExpFloat64", r.ExpFloat64(), r.ExpFloat64(), r.ExpFloat64()) 38 39 // NormFloat64 values have an average of 0 and a standard deviation of 1. 40 show("NormFloat64", r.NormFloat64(), r.NormFloat64(), r.NormFloat64()) 41 42 // Int31, Int63, and Uint32 generate values of the given width. 43 // The Int method (not shown) is like either Int31 or Int63 44 // depending on the size of 'int'. 45 show("Int31", r.Int31(), r.Int31(), r.Int31()) 46 show("Int63", r.Int63(), r.Int63(), r.Int63()) 47 show("Uint32", r.Int63(), r.Int63(), r.Int63()) 48 49 // Intn, Int31n, and Int63n limit their output to be < n. 50 // They do so more carefully than using r.Int()%n. 51 show("Intn(10)", r.Intn(10), r.Intn(10), r.Intn(10)) 52 show("Int31n(10)", r.Int31n(10), r.Int31n(10), r.Int31n(10)) 53 show("Int63n(10)", r.Int63n(10), r.Int63n(10), r.Int63n(10)) 54 55 // Perm generates a random permutation of the numbers [0, n). 56 show("Perm", r.Perm(5), r.Perm(5), r.Perm(5)) 57 // Output: 58 // Float32 0.2635776 0.6358173 0.6718283 59 // Float64 0.628605430454327 0.4504798828572669 0.9562755949377957 60 // ExpFloat64 0.3362240648200941 1.4256072328483647 0.24354758816173044 61 // NormFloat64 0.17233959114940064 1.577014951434847 0.04259129641113857 62 // Int31 1501292890 1486668269 182840835 63 // Int63 3546343826724305832 5724354148158589552 5239846799706671610 64 // Uint32 5927547564735367388 637072299495207830 4128311955958246186 65 // Intn(10) 1 2 5 66 // Int31n(10) 4 7 8 67 // Int63n(10) 7 6 3 68 // Perm [1 4 2 3 0] [4 2 1 3 0] [1 2 4 0 3] 69 }