github.com/lingyao2333/mo-zero@v1.4.1/core/mathx/proba.go (about) 1 package mathx 2 3 import ( 4 "math/rand" 5 "sync" 6 "time" 7 ) 8 9 // A Proba is used to test if true on given probability. 10 type Proba struct { 11 // rand.New(...) returns a non thread safe object 12 r *rand.Rand 13 lock sync.Mutex 14 } 15 16 // NewProba returns a Proba. 17 func NewProba() *Proba { 18 return &Proba{ 19 r: rand.New(rand.NewSource(time.Now().UnixNano())), 20 } 21 } 22 23 // TrueOnProba checks if true on given probability. 24 func (p *Proba) TrueOnProba(proba float64) (truth bool) { 25 p.lock.Lock() 26 truth = p.r.Float64() < proba 27 p.lock.Unlock() 28 return 29 }