go-zero/core/mathx/unstable.go

46 lines
1.0 KiB
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package mathx
import (
"math/rand"
"sync"
"time"
)
2022-11-04 21:55:17 +08:00
// An Unstable is used to generate random value around the mean value base on given deviation.
2020-07-26 17:09:05 +08:00
type Unstable struct {
deviation float64
r *rand.Rand
lock *sync.Mutex
}
2022-11-04 21:55:17 +08:00
// NewUnstable returns an Unstable.
2020-07-26 17:09:05 +08:00
func NewUnstable(deviation float64) Unstable {
if deviation < 0 {
deviation = 0
}
if deviation > 1 {
deviation = 1
}
return Unstable{
deviation: deviation,
r: rand.New(rand.NewSource(time.Now().UnixNano())),
lock: new(sync.Mutex),
}
}
2021-02-21 20:47:01 +08:00
// AroundDuration returns a random duration with given base and deviation.
2020-07-26 17:09:05 +08:00
func (u Unstable) AroundDuration(base time.Duration) time.Duration {
u.lock.Lock()
val := time.Duration((1 + u.deviation - 2*u.deviation*u.r.Float64()) * float64(base))
u.lock.Unlock()
return val
}
2021-05-04 21:33:08 +08:00
// AroundInt returns a random int64 with given base and deviation.
2020-07-26 17:09:05 +08:00
func (u Unstable) AroundInt(base int64) int64 {
u.lock.Lock()
val := int64((1 + u.deviation - 2*u.deviation*u.r.Float64()) * float64(base))
u.lock.Unlock()
return val
}