Unbias a random generator: Difference between revisions

Content added Content deleted
(Go solution)
Line 253: Line 253:
# [ 5, 200532, 500448 ],
# [ 5, 200532, 500448 ],
# [ 6, 166746, 499859 ] ]</lang>
# [ 6, 166746, 499859 ] ]</lang>
=={{header|Go}}==
<lang go>package main

import (
"fmt"
"rand"
)

const samples = 1e6

func main() {
fmt.Println("Generator 1 count 0 count % 1 count")
for n := 3; n <= 6; n++ {
// function randN, per task description
randN := func() int {
if rand.Intn(n) == 0 {
return 1
}
return 0
}
var b [2]int
for x := 0; x < samples; x++ {
b[randN()]++
}
fmt.Printf("randN(%d) %7d %7d %5.2f%%\n",
n, b[1], b[0], float64(b[1])*100/samples)

// function unbiased, per task description
unbiased := func() (b int) {
for b = randN(); b == randN(); b = randN() {
}
return
}
var u [2]int
for x := 0; x < samples; x++ {
u[unbiased()]++
}
fmt.Printf("unbiased %7d %7d %5.2f%%\n",
u[1], u[0], float64(u[1])*100/samples)
}
}</lang>
Output:
<pre>
Generator 1 count 0 count % 1 count
randN(3) 332711 667289 33.27%
unbiased 499649 500351 49.96%
randN(4) 249742 750258 24.97%
unbiased 499434 500566 49.94%
randN(5) 200318 799682 20.03%
unbiased 499100 500900 49.91%
randN(6) 166900 833100 16.69%
unbiased 499973 500027 50.00%
</pre>


=={{header|J}}==
=={{header|J}}==