maxwell Syndicate content

warning: Creating default object from empty value in /www/htdocs/w0065fc9/milianw/modules/taxonomy/taxonomy.pages.inc on line 33.

» Maxwell distribution in C++11

Tue, 07/29/2014 - 11:51

Hey all,

I recently needed to generate values following a Maxwell distribution. Wikipedia gives the hint that this is a Gamma distribution, which in C++11 is easily useable. Thus, thanks to <random>, we can setup a Maxwell distribution in a few lines of code:

  1. #include <random>
  2. #include <chrono>
  3. #include <iostream>
  4.  
  5. using namespace std;
  6.  
  7. int main()
  8. {
  9. unsigned seed = chrono::system_clock::now().time_since_epoch().count();
  10. default_random_engine generator(seed);
  11.  
  12. // Boltzmann factor times temperature
  13. const double k_T = 0.1;
  14.  
  15. // setup the Maxwell distribution, i.e. gamma distribution with alpha = 3/2
  16. gamma_distribution<double> maxwell(3./2., k_T);
  17.  
  18. // generate Maxwell-distributed values
  19. for (int i = 0; i < 10000; ++i) {
  20. cout << maxwell(generator) << endl;
  21. }
  22.  
  23. return 0;
  24. }

Pretty neat, I have to say!