Skip to content

WeightedIndex produces unexpected results when sum of weights does not fit in the integer type #1309

@tibordp

Description

@tibordp

WeightedIndex distribution does not explicitely check that the sum of weights fits into the target type X (if it is an integer). When compiling in release mode (with overflow checking disabled), this code will almost always print 0 rather than the expected 1.

use rand::thread_rng;
use rand_distr::{WeightedIndex, Distribution};

fn main() {
    let dist = WeightedIndex::new([2, usize::MAX]).unwrap();
    println!("{}", dist.sample(&mut thread_rng()));
}

I would expect WeightedIndex::new to either return an Err or panic if the sum of weights does not fit into X.

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