3 回答
TA贡献1786条经验 获得超13个赞
int sum_of_weight = 0;for(int i=0; i<num_choices; i++) { sum_of_weight += choice_weight[i];}int rnd = random(sum_of_weight);for(int i=0; i<num_choices; i++) { if(rnd < choice_weight[i]) return i; rnd -= choice_weight[i];}assert(!"should never get here");
TA贡献2080条经验 获得超4个赞
discrete_distribution
#include <random>#include <vector>std::vector<double> weights{90,56,4};std::discrete_distribution<int> dist(std::begin(weights), std::end(weights));std::mt19937 gen;gen.seed(time(0)); //if you want different results from different runsint N = 100000;std::vector<int> samples(N);for(auto & i: samples) i = dist(gen);//do something with your samples...
discrete_distribution
/usr/include/c++/5/bits/random.tcc
template<typename _IntType> void discrete_distribution<_IntType>::param_type:: _M_initialize() { if (_M_prob.size() < 2) { _M_prob.clear(); return; } const double __sum = std::accumulate(_M_prob.begin(), _M_prob.end(), 0.0); // Now normalize the probabilites. __detail::__normalize(_M_prob.begin(), _M_prob.end(), _M_prob.begin(), __sum); // Accumulate partial sums. _M_cp.reserve(_M_prob.size()); std::partial_sum(_M_prob.begin(), _M_prob.end(), std::back_inserter(_M_cp)); // Make sure the last cumulative probability is one. _M_cp[_M_cp.size() - 1] = 1.0; }
- 3 回答
- 0 关注
- 487 浏览
添加回答
举报