-
Notifications
You must be signed in to change notification settings - Fork 16
/
exponential.go
32 lines (27 loc) · 882 Bytes
/
exponential.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package rng
import (
"fmt"
"math"
)
// ExpGenerator is a random number generator for exponential distribution.
// The zero value is invalid, use NewExpGenerator to create a generator
type ExpGenerator struct {
uniform *UniformGenerator
}
// NewExpGenerator returns a exponential-distribution generator
// it is recommended using time.Now().UnixNano() as the seed, for example:
// erng := rng.NewExpGenerator(time.Now().UnixNano())
func NewExpGenerator(seed int64) *ExpGenerator {
urng := NewUniformGenerator(seed)
return &ExpGenerator{urng}
}
// Exp returns a random number of exponential distribution
func (erng ExpGenerator) Exp(lambda float64) float64 {
if !(lambda > 0.0) {
panic(fmt.Sprintf("Invalid lambda: %.2f", lambda))
}
return erng.exp(lambda)
}
func (erng ExpGenerator) exp(lambda float64) float64 {
return -math.Log(1-erng.uniform.Float64()) / lambda
}