Modified random distribution: Difference between revisions

Added Go
(Added Wren)
(Added Go)
Line 23:
 
Show your output here, on this page.
 
=={{header|Go}}==
{{trans|Wren}}
<lang go>package main
 
import (
"fmt"
"math"
"math/rand"
"strings"
"time"
)
 
func rng(modifier func(x float64) float64) float64 {
for {
r1 := rand.Float64()
r2 := rand.Float64()
if r2 < modifier(r1) {
return r1
}
}
}
 
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
 
func main() {
rand.Seed(time.Now().UnixNano())
modifier := func(x float64) float64 {
if x < 0.5 {
return 2 * (0.5 - x)
}
return 2 * (x - 0.5)
}
const (
N = 100000
NUM_BINS = 20
HIST_CHAR = "■"
HIST_CHAR_SIZE = 125
)
bins := make([]int, NUM_BINS) // all zero by default
binSize := 1.0 / NUM_BINS
for i := 0; i < N; i++ {
rn := rng(modifier)
bn := int(math.Floor(rn / binSize))
bins[bn]++
}
 
fmt.Println("Modified random distribution with", commatize(N), "samples in range [0, 1):\n")
fmt.Println(" Range Number of samples within that range")
for i := 0; i < NUM_BINS; i++ {
hist := strings.Repeat(HIST_CHAR, int(math.Round(float64(bins[i])/HIST_CHAR_SIZE)))
fi := float64(i)
fmt.Printf("%4.2f ..< %4.2f %s %s\n", binSize*fi, binSize*(fi+1), hist, commatize(bins[i]))
}
}</lang>
 
{{out}}
Specimen run:
<pre>
Modified random distribution with 100,000 samples in range [0, 1):
 
Range Number of samples within that range
0.00 ..< 0.05 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ 9,396
0.05 ..< 0.10 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ 8,434
0.10 ..< 0.15 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ 7,484
0.15 ..< 0.20 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ 6,576
0.20 ..< 0.25 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ 5,516
0.25 ..< 0.30 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ 4,625
0.30 ..< 0.35 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■ 3,478
0.35 ..< 0.40 ■■■■■■■■■■■■■■■■■■■■ 2,506
0.40 ..< 0.45 ■■■■■■■■■■■■ 1,504
0.45 ..< 0.50 ■■■■ 505
0.50 ..< 0.55 ■■■■ 511
0.55 ..< 0.60 ■■■■■■■■■■■■■ 1,563
0.60 ..< 0.65 ■■■■■■■■■■■■■■■■■■■■■ 2,582
0.65 ..< 0.70 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■ 3,520
0.70 ..< 0.75 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ 4,326
0.75 ..< 0.80 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ 5,489
0.80 ..< 0.85 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ 6,589
0.85 ..< 0.90 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ 7,472
0.90 ..< 0.95 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ 8,592
0.95 ..< 1.00 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ 9,332
</pre>
 
=={{header|Julia}}==
9,485

edits