Weighted random numbers

前端 未结 6 840
情书的邮戳
情书的邮戳 2020-11-22 08:50

I\'m trying to implement a weighted random numbers. I\'m currently just banging my head against the wall and cannot figure this out.

In my project (Hold\'em hand-ran

6条回答
  •  无人共我
    2020-11-22 09:18

    Choose a random number on [0,1), which should be the default operator() for a boost RNG. Choose the item with cumulative probability density function >= that number:

    template 
    It choose_p(It begin,It end,P const& p)
    {
        if (begin==end) return end;
        double sum=0.;
        for (It i=begin;i!=end;++i)
            sum+=p(*i);
        double choice=sum*random01();
        for (It i=begin;;) {
            choice -= p(*i);
            It r=i;
            ++i;
            if (choice<0 || i==end) return r;
        }
        return begin; //unreachable
    }
    

    Where random01() returns a double >=0 and <1. Note that the above doesn't require the probabilities to sum to 1; it normalizes them for you.

    p is just a function assigning a probability to an item in the collection [begin,end). You can omit it (or use an identity) if you just have a sequence of probabilities.

提交回复
热议问题