#alias #weighted #walker #random #methods

weighted_rand

使用Walker的别名方法的加权随机抽样库

7个不稳定版本

0.4.2 2023年10月1日
0.4.1 2023年7月3日
0.3.2 2021年11月11日
0.2.0 2021年11月8日
0.1.0 2021年11月7日

#1 in #weighted

Download history 119/week @ 2024-04-07 79/week @ 2024-04-14 116/week @ 2024-04-21 46/week @ 2024-04-28 52/week @ 2024-05-05 48/week @ 2024-05-12 56/week @ 2024-05-19 55/week @ 2024-05-26 56/week @ 2024-06-02 25/week @ 2024-06-09 53/week @ 2024-06-16 52/week @ 2024-06-23 121/week @ 2024-06-30 51/week @ 2024-07-07 70/week @ 2024-07-14 34/week @ 2024-07-21

278 每月下载量
用于 4 crates

MIT/Apache

19KB
263

weighted_rand

weighted_rand Crates.io docs.rs Crates.io

使用Walker的别名方法的加权随机抽样库。

Walker的别名方法(WAM)是进行加权随机抽样的一种方法。
WAM通过提供两块信息对数组的每个索引进行加权:指向不同索引的别名和决定是否跳转到该索引的概率。

WAM是一个非常快的算法,其搜索的计算复杂度为O(1)。
WAM与累积和方法的复杂度差异如下。

算法 构建表 搜索
Walker的别名方法 O(N) O(1)
累积和方法 O(N) O(log N)

API文档在此处https://docs.rs/weighted_rand

用法

将此添加到您的Cargo.toml中

[dependencies]
weighted_rand = "0.4"

示例

use weighted_rand::builder::WalkerTableBuilder;

fn main() {
    let fruit = ["Apple", "Banana", "Orange", "Peach"];

    // Define the weights for each index corresponding
    // to the above list.
    // In the following case, the ratio of each weight
    // is "2 : 1 : 7 : 0", and the output probabilities
    // for each index are 0.2, 0.1, 0.7 and 0.
    let index_weights = [2, 1, 7, 0];

    let builder = WalkerTableBuilder::new(&index_weights);
    let wa_table = builder.build();

    for i in (0..10).map(|_| wa_table.next()) {
        println!("{}", fruit[i]);
    }
}

此外,index_weiaghts支持&[f32],例如

use rand;
use weighted_rand::builder::*;

fn main() {
    // Coin with a 5% higher probability of heads than tails
    let cheating_coin = ["Heads!", "Tails!"];
    let index_weights = [0.55, 0.45];

    let builder = WalkerTableBuilder::new(&index_weights);
    let wa_table = builder.build();

    // If you want to process something in a large number of
    // loops, we recommend using the next_rng method with an
    // external ThreadRng instance.
    let mut result = [""; 10000];
    let mut rng = rand::thread_rng();
    for r in &mut result {
        let j = wa_table.next_rng(&mut rng);
        *r = cheating_coin[j];
    }

    // println!("{:?}", result);
}

许可证

许可协议为以下之一

任选其一。

贡献

除非您明确声明,否则任何有意提交以包含在您的工作中的贡献,根据Apache-2.0许可证定义,应按上述方式双许可,不附加任何额外条款或条件。

依赖关系

~0.7–1.3MB
~29K SLoC