Skip to content

Instantly share code, notes, and snippets.

@arielshaqed
Last active January 12, 2021 11:44
Show Gist options
  • Save arielshaqed/3a0080cfdad52a7086d133162b277efa to your computer and use it in GitHub Desktop.
Save arielshaqed/3a0080cfdad52a7086d133162b277efa to your computer and use it in GitHub Desktop.
simulate range sizes with a log-normal path size distribution
package main
import (
"fmt"
"math"
"time"
"golang.org/x/exp/rand"
"gonum.org/v1/gonum/stat/distuv"
)
// trial runs a single trial of sampling a value X from rv and using r to stop with probabilty
// t/X.
func trial(r *rand.Rand, rv func() float64, t float64) int {
for i := 1; ; i++ {
x := rv()
if r.Float64() < t/x {
return i
}
}
}
// expected estimates the expected value of trial.
func expected(trialer func() int) float64 {
const n = 50000
sum := 0
for i := 0; i < n; i++ {
sum += trialer()
}
return float64(sum) / float64(n)
}
func main() {
// estimate the expected value of a stopping time
source := rand.NewSource(uint64(time.Now().UnixNano()))
n := &distuv.LogNormal{
Mu: 7.0,
Sigma: 2,
Src: source,
}
r := rand.New(source)
num := expected(func() int {
return trial(r, n.Rand, 1)
})
fmt.Println("stop: ", num)
avg := expected(func() int {
return int(math.Ceil(n.Rand()))
})
fmt.Println("value: ", avg)
fmt.Println("total size: ", num*avg)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment