You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/core/mathx/proba.go

30 lines
534 B
Go

4 years ago
package mathx
import (
"math/rand"
"sync"
"time"
)
// A Proba is used to test if true on given probability.
4 years ago
type Proba struct {
// rand.New(...) returns a non thread safe object
r *rand.Rand
lock sync.Mutex
}
// NewProba returns a Proba.
4 years ago
func NewProba() *Proba {
return &Proba{
r: rand.New(rand.NewSource(time.Now().UnixNano())),
}
}
// TrueOnProba checks if true on given probability.
4 years ago
func (p *Proba) TrueOnProba(proba float64) (truth bool) {
p.lock.Lock()
truth = p.r.Float64() < proba
p.lock.Unlock()
return
}