Support for weights in choosing a random element from values


#1

Rng::choose and rand::sample don’t accept weights for each element, which is pretty sad.

Ideally I would be able to do something like this:

use rand::{thread_rng, Rng};

let choices = [1, 2, 4, 8, 16, 32];
let weights = [0.1, 0.1, 0.1, 0.2, 0.5];
let mut rng = thread_rng();
println!("{:?}", rng.choose(&choices, &weights));

Would such feature be helpful for the others? Is there any chance rand crate developers would get to that or is it fine if I try to implement it myself and submit it to the crate?


#2

Yes, I implemented such a crate. It’s named Rust Random Choice.
For curiosity: May I ask your use case?


#3

rand already has WeightedChoice, does that work for you?


#4

Ah. Yes, it does. Apologies for inconvenience then.


#5

However, it makes weights proportional to u32 values. It’s not as useful as having “raw” probabilities. Or at least floats…


#6

@StefanoD’s random_choice crate looks like it supports floating point probabilities.


#7

Yep, makes sense. Thanks again.

I wonder why it wasn’t simply contributed to the rand crate. I’m very new to rust, but rand seems to be “standard” to some extent.


#8

I wanted to contribute it, but see the answer yourself.


#9

Ah, I see. That’s sad. Thank you for the crate!

As for my use case: I’m implementing KMeans++.