random_vector.hpp 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // (C) Copyright Nick Thompson 2018.
  2. // (C) Copyright Matt Borland 2021.
  3. // Use, modification and distribution are subject to the
  4. // Boost Software License, Version 1.0. (See accompanying file
  5. // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. #include <vector>
  7. #include <random>
  8. #include <type_traits>
  9. #include <cstddef>
  10. namespace boost { namespace math {
  11. // To stress test, set global_seed = 0, global_size = huge.
  12. static const std::size_t global_seed = 0;
  13. static const std::size_t global_size = 128;
  14. template<typename T, typename std::enable_if<std::is_floating_point<T>::value, bool>::type = true>
  15. std::vector<T> generate_random_vector(std::size_t size, std::size_t seed)
  16. {
  17. if (seed == 0)
  18. {
  19. std::random_device rd;
  20. seed = rd();
  21. }
  22. std::vector<T> v(size);
  23. std::mt19937 gen(seed);
  24. std::normal_distribution<T> dis(0, 1);
  25. for(std::size_t i = 0; i < v.size(); ++i)
  26. {
  27. v[i] = dis(gen);
  28. }
  29. return v;
  30. }
  31. template<typename T, typename std::enable_if<std::is_integral<T>::value, bool>::type = true>
  32. std::vector<T> generate_random_vector(std::size_t size, std::size_t seed)
  33. {
  34. if (seed == 0)
  35. {
  36. std::random_device rd;
  37. seed = rd();
  38. }
  39. std::vector<T> v(size);
  40. std::mt19937 gen(seed);
  41. // Rescaling by larger than 2 is UB!
  42. std::uniform_int_distribution<T> dis(std::numeric_limits<T>::lowest()/2, (std::numeric_limits<T>::max)()/2);
  43. for (std::size_t i = 0; i < v.size(); ++i)
  44. {
  45. v[i] = dis(gen);
  46. }
  47. return v;
  48. }
  49. }} // Namesapces