Code SnippetsMaxwell distribution in C++11 Syndicate content

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!

Comments

Post new comment

  • You can use Markdown syntax to format and style the text. Also see Markdown Extra for tables, footnotes, and more.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <pre>.
  • Web page addresses and e-mail addresses turn into links automatically.

More information about formatting options