proba.go 534 B

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