Black Lives Matter. Support the Equal Justice Initiative.

Source file src/math/rand/gen_cooked.go

Documentation: math/rand

     1  // Copyright 2009 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  //go:build ignore
     6  // +build ignore
     7  
     8  // This program computes the value of rngCooked in rng.go,
     9  // which is used for seeding all instances of rand.Source.
    10  // a 64bit and a 63bit version of the array is printed to
    11  // the standard output.
    12  
    13  package main
    14  
    15  import "fmt"
    16  
    17  const (
    18  	length = 607
    19  	tap    = 273
    20  	mask   = (1 << 63) - 1
    21  	a      = 48271
    22  	m      = (1 << 31) - 1
    23  	q      = 44488
    24  	r      = 3399
    25  )
    26  
    27  var (
    28  	rngVec          [length]int64
    29  	rngTap, rngFeed int
    30  )
    31  
    32  func seedrand(x int32) int32 {
    33  	hi := x / q
    34  	lo := x % q
    35  	x = a*lo - r*hi
    36  	if x < 0 {
    37  		x += m
    38  	}
    39  	return x
    40  }
    41  
    42  func srand(seed int32) {
    43  	rngTap = 0
    44  	rngFeed = length - tap
    45  	seed %= m
    46  	if seed < 0 {
    47  		seed += m
    48  	} else if seed == 0 {
    49  		seed = 89482311
    50  	}
    51  	x := seed
    52  	for i := -20; i < length; i++ {
    53  		x = seedrand(x)
    54  		if i >= 0 {
    55  			var u int64
    56  			u = int64(x) << 20
    57  			x = seedrand(x)
    58  			u ^= int64(x) << 10
    59  			x = seedrand(x)
    60  			u ^= int64(x)
    61  			rngVec[i] = u
    62  		}
    63  	}
    64  }
    65  
    66  func vrand() int64 {
    67  	rngTap--
    68  	if rngTap < 0 {
    69  		rngTap += length
    70  	}
    71  	rngFeed--
    72  	if rngFeed < 0 {
    73  		rngFeed += length
    74  	}
    75  	x := (rngVec[rngFeed] + rngVec[rngTap])
    76  	rngVec[rngFeed] = x
    77  	return x
    78  }
    79  
    80  func main() {
    81  	srand(1)
    82  	for i := uint64(0); i < 7.8e12; i++ {
    83  		vrand()
    84  	}
    85  	fmt.Printf("rngVec after 7.8e12 calls to vrand:\n%#v\n", rngVec)
    86  	for i := range rngVec {
    87  		rngVec[i] &= mask
    88  	}
    89  	fmt.Printf("lower 63bit of rngVec after 7.8e12 calls to vrand:\n%#v\n", rngVec)
    90  }
    91  

View as plain text