0

I need to generate random numbers representing user activities using chi square distribution in (boost) tr1 c++. Any example or help on how would I start?


I tried the following code:

int main (){
    std::tr1::mt19937 eng; // a core engine class 
                           //mt19937 is a very fast random number generator algorithm 
    eng.seed(time(0));   //each engine has a seed method 

    //file to store seed 
    std::tr1::chi_squared_distribution<double> chdist(5.0); 
    cout<<endl<<"CHIDIST"<<endl<<"================"<<endl; 

    for (int i = 0; i<50; ++i) 
    { 
         Act.push_back(chdist(eng)*0.1); 
         int rounded = ((int)(chdist(eng) * 100 + .5) / 100.0);         
         Act.push_back(rounded*0.1); cout<<Act[i]<< endl; 
    }

     return 0;   
}
Bo Persson
  • 90,663
  • 31
  • 146
  • 203
  • Another related post here http://stackoverflow.com/questions/795972/homebrew-chi-squared-probability-function-in-c – MARK Nov 28 '11 at 14:41
  • I tried the following code: int main (){std::tr1::mt19937 eng; // a core engine class //mt19937 is a very fast random number generator algorithm eng.seed(time(0)); //each engine has a seed method //file to store seed std::tr1::chi_squared_distribution chdist(5.0); cout< – user1066351 Nov 28 '11 at 15:30
  • You should include your code as a question edit, not a comment. Use the code icon for formatting. – Steve Townsend Nov 28 '11 at 17:19

1 Answers1

2

From Wikipedia:

If Z1, ..., Zk are independent, standard normal random variables, then the sum of their squares is distributed according to the chi-squared distribution

so you may want to generate k standard normal variables and calculate their sum squared.

varepsilon
  • 488
  • 5
  • 8
  • I need to implement the chi-square distribution in c++ to generate random user activities. – user1066351 Nov 28 '11 at 15:07
  • There are many ways to generate normally distributed variables (check out this thread: http://stackoverflow.com/questions/2325472/generate-random-numbers-following-a-normal-distribution-in-c-c). After that you can easily generate chi-square distribution by calculating sum of their squares. – varepsilon Nov 28 '11 at 15:39