github.com/xaionaro-go/rand@v0.0.0-20191005105903-aba1befc54a5/mathrand/reduce32.go (about)

     1  package mathrand
     2  
     3  // ReduceUint32 returns `src` as a value smaller than `mod`.
     4  //
     5  // Based on: http://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/
     6  //
     7  // For fair distribution of results `src` shouldn't be reduced,
     8  // it should be an uint32 mathrandom number [0..2^32).
     9  func ReduceUint32(src, mod uint32) uint32 {
    10  	// http://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/
    11  	return uint32(((uint64)(src) * uint64(mod)) >> 32)
    12  }