github.com/zuoyebang/bitalostable@v1.0.1-0.20240229032404-e3b99a834294/internal/randvar/uniform.go (about) 1 // Copyright 2018 The Cockroach Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 12 // implied. See the License for the specific language governing 13 // permissions and limitations under the License. See the AUTHORS file 14 // for names of contributors. 15 16 package randvar 17 18 import ( 19 "sync/atomic" 20 21 "golang.org/x/exp/rand" 22 ) 23 24 // Uniform is a random number generator that generates draws from a uniform 25 // distribution. 26 type Uniform struct { 27 min uint64 28 max uint64 29 } 30 31 // NewUniform constructs a new Uniform generator with the given 32 // parameters. Returns an error if the parameters are outside the accepted 33 // range. 34 func NewUniform(min, max uint64) *Uniform { 35 return &Uniform{min: min, max: max} 36 } 37 38 // IncMax increments max. 39 func (g *Uniform) IncMax(delta int) { 40 atomic.AddUint64(&g.max, uint64(delta)) 41 } 42 43 // Max returns the max value of the distribution. 44 func (g *Uniform) Max() uint64 { 45 return atomic.LoadUint64(&g.max) 46 } 47 48 // Uint64 returns a random Uint64 between min and max, drawn from a uniform 49 // distribution. 50 func (g *Uniform) Uint64(rng *rand.Rand) uint64 { 51 max := atomic.LoadUint64(&g.max) 52 return rng.Uint64n(max-g.min+1) + g.min 53 }