Skip to content

Commit

Permalink
add function ExponentialRandom to generate random number following Ex…
Browse files Browse the repository at this point in the history
…ponential Distribution
  • Loading branch information
Weifan Zhang committed Nov 23, 2022
1 parent 0286b1d commit 62929d0
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
20 changes: 20 additions & 0 deletions random/random.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,3 +114,23 @@ func RandomPickN(a []int, m int) []int {
}
return result
}

// ExponentialRandom generate a random number following Exponential Distribution, use rand.Seed in init() of this file
// range is [lowerBound, upperBound] and the expectation is 1/lambda.
// lambda is "rate parameter"
func ExponentialRandom(lowerBound, upperBound float64, lambda float64) float64 {
if lowerBound > upperBound || float64(1)/lambda < lowerBound || float64(1)/lambda > upperBound {
return -1
}
if !(lambda > 0) {
return -1 // lambda must be larger than 0
}
var result float64
for {
result = rand.ExpFloat64() * 1 / lambda
if result <= upperBound && result >= lowerBound {
break
}
}
return result
}
11 changes: 11 additions & 0 deletions random/random_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,3 +134,14 @@ func TestRandomPickN(t *testing.T) {
testInt := []int{1, 2, 3, 4, 5, 3, 3, 3, 3, 3, 3, 3}
t.Log(RandomPickN(testInt, 7))
}

func TestExponentialRandom(t *testing.T) {
fmt.Println("Generate 40 Exponential random float64 in [10,20]:")
for i := 0; i < 40; i++ {
fmt.Println(ExponentialRandom(3, 35, float64(1)/float64(15)))
}
fmt.Println("Generate 40 Exponential random float64 in [0,max]:")
for i := 0; i < 40; i++ {
fmt.Println(ExponentialRandom(0, math.MaxFloat64, float64(1)/float64(15)))
}
}

0 comments on commit 62929d0

Please sign in to comment.