boostrandomgen.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // a random number generator supporting different distributions.
  2. //
  3. // Copyright Steven Ross 2009.
  4. //
  5. // Distributed under the Boost Software License, Version 1.0.
  6. // (See accompanying file LICENSE_1_0.txt or copy at
  7. // http://www.boost.org/LICENSE_1_0.txt)
  8. // See http://www.boost.org/libs/sort for library home page.
  9. #include <stdio.h>
  10. #include "stdlib.h"
  11. #include <fstream>
  12. #include <iostream>
  13. #include <vector>
  14. #include <string>
  15. #include <boost/random.hpp>
  16. using std::string;
  17. using namespace boost;
  18. int main(int argc, const char ** argv) {
  19. //Always seed with the same value, to get the same results
  20. srand(1);
  21. //defaults
  22. int mod_shift = 32;
  23. unsigned count = 1000000;
  24. //Reading in user arguments
  25. if (argc > 2)
  26. count = atoi(argv[2]);
  27. if (argc > 1)
  28. mod_shift = atoi(argv[1]) - 1;
  29. std::ofstream ofile;
  30. ofile.open("input.txt", std::ios_base::out | std::ios_base::binary |
  31. std::ios_base::trunc);
  32. if (ofile.bad()) {
  33. printf("could not open input.txt for writing!\n");
  34. return 1;
  35. }
  36. int min_int = (std::numeric_limits<int>::min)();
  37. int max_int = (std::numeric_limits<int>::max)();
  38. if (mod_shift < 31 && mod_shift >= 0) {
  39. max_int %= 1 << mod_shift;
  40. if (-max_int > min_int)
  41. min_int = -max_int;
  42. }
  43. std::vector<int> result;
  44. result.resize(count);
  45. mt19937 rng;
  46. if (argc > 3 && (string(argv[3]) == "-normal")) {
  47. boost::normal_distribution<> everything(0, max_int/4);
  48. variate_generator<mt19937&,normal_distribution<> > gen(rng, everything);
  49. generate(result.begin(), result.end(), gen);
  50. }
  51. else if (argc > 3 && (string(argv[3]) == "-lognormal")) {
  52. lognormal_distribution<> everything(max_int/2, max_int/4);
  53. variate_generator<mt19937&,lognormal_distribution<> > gen(rng, everything);
  54. generate(result.begin(), result.end(), gen);
  55. }
  56. else {
  57. uniform_int<> everything(min_int, max_int);
  58. variate_generator<mt19937&,uniform_int<> > gen(rng, everything);
  59. generate(result.begin(), result.end(), gen);
  60. }
  61. ofile.write(reinterpret_cast<char *>(&(result[0])), result.size() *
  62. sizeof(int));
  63. ofile.close();
  64. return 0;
  65. }