go-zero/core/mathx/proba.go

30 lines
534 B
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package mathx
import (
"math/rand"
"sync"
"time"
)
2021-02-21 20:47:01 +08:00
// A Proba is used to test if true on given probability.
2020-07-26 17:09:05 +08:00
type Proba struct {
// rand.New(...) returns a non thread safe object
r *rand.Rand
lock sync.Mutex
}
2021-02-21 20:47:01 +08:00
// NewProba returns a Proba.
2020-07-26 17:09:05 +08:00
func NewProba() *Proba {
return &Proba{
r: rand.New(rand.NewSource(time.Now().UnixNano())),
}
}
2021-02-21 20:47:01 +08:00
// TrueOnProba checks if true on given probability.
2020-07-26 17:09:05 +08:00
func (p *Proba) TrueOnProba(proba float64) (truth bool) {
p.lock.Lock()
truth = p.r.Float64() < proba
p.lock.Unlock()
return
}