Support for weights in choosing a random element from values

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 Likes

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

1 Like

rand already has WeightedChoice, does that work for you?

2 Likes

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

However, it makes weights proportional to u32 values. It's not as useful as having "raw" probabilities. Or at least floats...

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

2 Likes

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.

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

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

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

1 Like