Skip to content

Is the SliceRandom::choose_weighted(...) method guaranteed to never choose an entry if it has zero weight? #1243

@ISibboI

Description

@ISibboI

The documentation does not mention issues related to entries with zero weight.

It would seem logical, that when the weight is integer, but it is zero, that the corresponding entry can never be chosen.
For example, I would assume that the following code cannot fail:

use rand::prelude::*;

pub fn main() {
    let list = [1, 2, 3, 0];

    assert_ne!(*list.choose_weighted(&mut thread_rng(), |number| *number).unwrap(), 0);
}

(playground)

And additionally, the same should hold for floating point numbers. But there I am less sure, because depending on the implementation maybe there are issues with rounding errors?

use rand::prelude::*;

pub fn main() {
    let list = [1.0, 2.0, 3.0, 0.0];

    assert_ne!(*list.choose_weighted(&mut thread_rng(), |number| *number).unwrap(), 0.0);
}

(playground)

  1. Is it true that the integer version cannot fail? If yes, could this be added to the documentation to make it an official guarantee?
  2. Is it true that the floating point version cannot fail? If yes, could this be added to the documentation to make it an official guarantee?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions