我正在尝试在非常窄的范围内生成多个随机 u32 整数。我的最大值和最小值实际上都在 1 到 6 之间变化。我想将发生器偏置到范围的中间。
我有tried using the Normal
distribution from the rand_distr
crate ,但它似乎适用于 float 和无界概率,即我想要 2 到 5 之间的值,但我可能会得到像 0.81 或 6.92 这样的结果,即使它们相当罕见。我无法在文档中找到正态分布的整数版本。我假设它不存在。
我也希望它是高效的,所以我有一种感觉 float 的正态分布性能不会很好。我还注意到一种称为加权索引的分布,但这需要每次迭代时手动计算权重。
也许在生成器运行后,整数值的常规 get_range
可能会以某种方式偏向算术平均值。有人对此有任何有趣的解决方案吗?
最佳答案
如果您想从值样本中获得有偏差的随机分布,可以使用 rand
crate 的rand::distributions::weighted::WeightedIndex
通过定义样本中每个项目的权重来对偏差进行精细控制。
use rand::prelude::*;
use rand::distributions::WeightedIndex;
fn main(){
let mut rng = thread_rng();
//item value and it's weight increasing till middle and then decreasing till end
let sample_item = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 3), ('f', 2), ('g', 1)];
let weight_dist = WeightedIndex::new(sample_item.iter().map(|(_, weight)| weight)).unwrap();
let mut pool = vec![];
for _ in 1..100{
let item = sample_item[weight_dist.sample(&mut rng)];
pool.push(item.0);
}
println!("{:?}", pool.iter().filter(|x| **x == 'a').count());
println!("{:?}", pool.iter().filter(|x| **x == 'b').count());
println!("{:?}", pool.iter().filter(|x| **x == 'c').count());
println!("{:?}", pool.iter().filter(|x| **x == 'd').count());
println!("{:?}", pool.iter().filter(|x| **x == 'e').count());
println!("{:?}", pool.iter().filter(|x| **x == 'f').count());
}
您可以尝试使用代码 here
关于random - 在偏向中间的范围内生成随机无符号整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59624635/