【问题标题】:How to randomly pick element from an array with different probabilities in C++如何在 C++ 中从具有不同概率的数组中随机选择元素
【发布时间】:2021-12-20 17:10:01
【问题描述】:

假设我有一些对象的vector<Point> p

我可以通过简单的p[rand() % p.size()] 随机选择一个。

现在假设我有另一个相同大小的双精度向量 vector <double> chances

我想从 p 中随机抽样,每个元素的概率类似于它在 chances 中的值(总和可能不是 1.0)。如何在 C++ 中实现这一点?

【问题讨论】:

  • 您可以使用std::discrete_distribution 获得一个根据您的chances 向量分布的整数,然后将该整数用作点向量的索引。
  • rand() % someNumber is not a uniform distribution.

标签: c++ random sampling


【解决方案1】:

您正在寻找std::discrete_distribution。忘记rand()

#include <random>
#include <vector>

struct Point {};

int main() {
    std::mt19937 gen(std::random_device{}());

    std::vector<double> chances{1.0, 2.0, 3.0};
    // Initialize to same length.
    std::vector<Point> points(chances.size());
    // size_t is suitable for indexing.
    std::discrete_distribution<std::size_t> d{chances.begin(), chances.end()};

    auto sampled_value = points[d(gen)];
}

为方便起见,权重之和不必为 1。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-25
    • 2013-03-11
    • 2014-03-22
    • 2020-07-29
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 2013-06-19
    相关资源
    最近更新 更多