Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Generate random number using Go standard library.
package main
import (
"flag"
"fmt"
"math/rand"
)
var (
Seed int64
Dist string
Size int
Lambda float64
K int
E string
)
func init() {
flag.Int64Var(&Seed, "seed", 1, "Seed")
flag.StringVar(&Dist, "dist", "", "Distribution")
flag.IntVar(&Size, "size", 1, "Size of random number")
flag.Float64Var(&Lambda, "lambda", 1.0, "Parameter lambda")
flag.IntVar(&K, "k", 1, "Parameter of shape")
flag.StringVar(&E, "e", "", "Expectation for Erlang distribution (1/lambda or k/lambda)")
}
func main() {
flag.Parse()
rnd := rand.New(rand.NewSource(Seed))
for i := 0; i < Size; i++ {
sample := 0.0
switch Dist {
case "exponential":
sample = Exponential(rnd, Lambda)
case "poisson":
sample = Poisson(rnd, Lambda)
case "erlang":
switch E {
case "k/l": // E[x] = k/lambda
sample = ErlangKL(rnd, Lambda, K)
case "1/l": // E[x] = 1/lambda
sample = Erlang1L(rnd, Lambda, K)
}
}
fmt.Println(sample)
}
}
func Exponential(rnd *rand.Rand, lambda float64) float64 {
return rnd.ExpFloat64() / lambda
}
func Poisson(rnd *rand.Rand, lambda float64) float64 {
p := 0.0
for i := 0; ; i++ {
p += Exponential(rnd, lambda)
if p >= 1.0 {
return float64(i)
}
}
return 0.0
}
func ErlangKL(rnd *rand.Rand, lambda float64, k int) float64 {
g := 0.0
for i := 0; i < k; i++ {
g += Exponential(rnd, lambda)
}
return g
}
func Erlang1L(rnd *rand.Rand, lambda float64, k int) float64 {
g := 0.0
for i := 0; i < k; i++ {
g += Exponential(rnd, float64(k)*lambda)
}
return g
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.