unstable.go 787 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package mathx
  2. import (
  3. "math/rand"
  4. "sync"
  5. "time"
  6. )
  7. type Unstable struct {
  8. deviation float64
  9. r *rand.Rand
  10. lock *sync.Mutex
  11. }
  12. func NewUnstable(deviation float64) Unstable {
  13. if deviation < 0 {
  14. deviation = 0
  15. }
  16. if deviation > 1 {
  17. deviation = 1
  18. }
  19. return Unstable{
  20. deviation: deviation,
  21. r: rand.New(rand.NewSource(time.Now().UnixNano())),
  22. lock: new(sync.Mutex),
  23. }
  24. }
  25. func (u Unstable) AroundDuration(base time.Duration) time.Duration {
  26. u.lock.Lock()
  27. val := time.Duration((1 + u.deviation - 2*u.deviation*u.r.Float64()) * float64(base))
  28. u.lock.Unlock()
  29. return val
  30. }
  31. func (u Unstable) AroundInt(base int64) int64 {
  32. u.lock.Lock()
  33. val := int64((1 + u.deviation - 2*u.deviation*u.r.Float64()) * float64(base))
  34. u.lock.Unlock()
  35. return val
  36. }