Unbias a random generator: Difference between revisions

→‎{{header|Rust}}: add Rust solution
(→‎{{header|Rust}}: add Rust solution)
Line 1,716:
5 199767 500354
6 166163 499809
</pre>
 
=={{header|Rust}}==
<lang Rust>#![feature(inclusive_range_syntax)]
 
extern crate rand;
 
use rand::Rng;
 
fn rand_n<R: Rng>(rng: &mut R, n: u32) -> usize {
rng.gen_weighted_bool(n) as usize // maps `false` to 0 and `true` to 1
}
 
fn unbiased<R: Rng>(rng: &mut R, n: u32) -> usize {
let mut bit = rand_n(rng, n);
while bit == rand_n(rng, n) {
bit = rand_n(rng, n);
}
bit
}
 
fn main() {
const SAMPLES: usize = 100_000;
let mut rng = rand::weak_rng();
 
println!(" Bias rand_n unbiased");
for n in 3..=6 {
let mut count_biased = 0;
let mut count_unbiased = 0;
for _ in 0..SAMPLES {
count_biased += rand_n(&mut rng, n);
count_unbiased += unbiased(&mut rng, n);
}
 
let b_percentage = 100.0 * count_biased as f64 / SAMPLES as f64;
let ub_percentage = 100.0 * count_unbiased as f64 / SAMPLES as f64;
println!(
"bias {}: {:0.2}% {:0.2}%",
n, b_percentage, ub_percentage
);
}
}</lang>
{{output}}
<pre>
Bias rand_n unbiased
bias 3: 33.32% 49.80%
bias 4: 25.22% 50.16%
bias 5: 19.91% 50.00%
bias 6: 16.66% 49.95%
</pre>