0

I have an array of probability for some actions identified by array index(e.g. like Boltzmann distribution )

for(int i=0;i<N_ACTIONS;i++)
        {
            p[i]=exp(q_tab[state()][i]/T);

            if(isnan(p[i]))
            {
                p[i]=0;
            }

        }
        long double s=p.sum();
        for(int i=0;i<N_ACTIONS;i++)   
        {
            p[i]=p[i]/s; 
        }

I have to choice a random number i between 0 and N_ACTIONS-1 with probability p[i]; I made this but doesn't seem working well:

int ChoiceFromDist(valarray<long double> p)
{
    int                   index=0;
    valarray<long double> cumulativa(p.size());

    cumulativa[0]=p[0];

    for(int i=1; i < p.size(); i++)
        cumulativa[i]  =  cumulativa[i-1]+p[i];

    long double num= ( (long double)rand()/(long double)RAND_MAX ); 

    while(index<p.size() && cumulativa[index]<num )
        index++;
    return index;
}

caller:

srand(time(0));
act=ChoiceFromDist(p);

It seems to choice always the same number (from 0 to 2 it choices 2) ....Do you see something wrong or the error coulbe in another code point? Thanks

6
  • 1
    Please show us the contents of p from a test where ChoiceFromDist didn't work as it should.
    – NPE
    Mar 23, 2013 at 13:52
  • I don't know if it will help, but you might want to read about the new pseudo-random facilities that came with the new C++11 standard. Mar 23, 2013 at 13:53
  • Check and tell us the numbers of p.size() and num.
    – SChepurin
    Mar 23, 2013 at 14:13
  • Are you calling srand(time(0)) before every call to ChoiceFromDist()? If so, then you are going to get the same result for every call that occurs during the same clock second and won't get a different result until the second hand ticks on the clock. You should call srand(time(0)) from main() and not call it again after that. Mar 23, 2013 at 14:16
  • nono...the srand(Tim(0)) is called just one time..I write it so that you see I don't forget it :)
    – volperossa
    Mar 23, 2013 at 15:50

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.