如何在 C++ 中从具有不同概率的数组中随机选择元素
How to randomly pick element from an array with different probabilities in C++
假设我有一些对象 vector<Point> p
。
我可以通过简单地 p[rand() % p.size()]
.
来随机选择一个
现在假设我有另一个相同大小的双精度向量 vector <double> chances
。
我想从 p 中随机抽样,每个元素的概率类似于它在 chances
中的值(总和可能不是 1.0)。我怎样才能在 C++ 中实现它?
您正在寻找 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。
假设我有一些对象 vector<Point> p
。
我可以通过简单地 p[rand() % p.size()]
.
现在假设我有另一个相同大小的双精度向量 vector <double> chances
。
我想从 p 中随机抽样,每个元素的概率类似于它在 chances
中的值(总和可能不是 1.0)。我怎样才能在 C++ 中实现它?
您正在寻找 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。