Debian Codegraph @

third-party/boost-math/include/boost/math/tools/random_vector.hpp

raw
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
7 #include <cstddef>
8 #include <random>
9 #include <type_traits>
10 #include <vector>
11
12 namespace boost { namespace math {
13
14 // To stress test, set global_seed = 0, global_size = huge.
15 static constexpr std::size_t global_seed = 0;
16 static constexpr std::size_t global_size = 128;
17
18 template<typename T, typename std::enable_if<std::is_floating_point<T>::value, bool>::type = true>
19 std::vector<T> generate_random_vector(std::size_t size, std::size_t seed)
20 {
21 if (seed == 0)
22 {
23 std::random_device rd;
24 seed = rd();
25 }
26 std::vector<T> v(size);
27
28 std::mt19937_64 gen(seed);
29
30 std::normal_distribution<T> dis(0, 1);
31 for (auto& x : v)
32 {
33 x = dis(gen);
34 }
35 return v;
36 }
37
38 template<typename T, typename std::enable_if<std::is_floating_point<T>::value, bool>::type = true>
39 std::vector<T> generate_random_uniform_vector(std::size_t size, std::size_t seed, T lower_bound = T(0), T upper_bound = T(1))
40 {
41 if (seed == 0)
42 {
43 std::random_device rd;
44 seed = rd();
45 }
46 std::vector<T> v(size);
47
48 std::mt19937 gen(seed);
49
50 std::uniform_real_distribution<T> dis(lower_bound, upper_bound);
51
52 for (auto& x : v)
53 {
54 x = dis(gen);
55 }
56
57 return v;
58 }
59
60 template<typename T, typename std::enable_if<std::is_floating_point<T>::value, bool>::type = true>
61 std::vector<T> generate_random_vector(std::size_t size, std::size_t seed, T mean, T stddev)
62 {
63 if (seed == 0)
64 {
65 std::random_device rd;
66 seed = rd();
67 }
68 std::vector<T> v(size);
69
70 std::mt19937 gen(seed);
71
72 std::normal_distribution<T> dis(mean, stddev);
73 for (auto& x : v)
74 {
75 x = dis(gen);
76 }
77 return v;
78 }
79
80 template<typename T, typename std::enable_if<std::is_integral<T>::value, bool>::type = true>
81 std::vector<T> generate_random_vector(std::size_t size, std::size_t seed)
82 {
83 if (seed == 0)
84 {
85 std::random_device rd;
86 seed = rd();
87 }
88 std::vector<T> v(size);
89
90 std::mt19937_64 gen(seed);
91
92 // Rescaling by larger than 2 is UB!
93 std::uniform_int_distribution<T> dis(std::numeric_limits<T>::lowest()/2, (std::numeric_limits<T>::max)()/2);
94 for (auto& x : v)
95 {
96 x = dis(gen);
97 }
98 return v;
99 }
100
101 }} // Namespaces