1 //===----------------------------------------------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is dual licensed under the MIT and the University of Illinois Open 6 // Source Licenses. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 // <random> 11 12 // template<class _IntType = int> 13 // class uniform_int_distribution 14 15 // template<class _URNG> result_type operator()(_URNG& g, const param_type& parm); 16 17 #include <random> 18 #include <cassert> 19 #include <vector> 20 #include <numeric> 21 22 template <class T> 23 inline 24 T sqr(T x)25sqr(T x) 26 { 27 return x * x; 28 } 29 main()30int main() 31 { 32 { 33 typedef std::uniform_int_distribution<> D; 34 typedef std::minstd_rand G; 35 typedef D::param_type P; 36 G g; 37 D d(5, 100); 38 P p(-10, 20); 39 const int N = 100000; 40 std::vector<D::result_type> u; 41 for (int i = 0; i < N; ++i) 42 { 43 D::result_type v = d(g, p); 44 assert(p.a() <= v && v <= p.b()); 45 u.push_back(v); 46 } 47 double mean = std::accumulate(u.begin(), u.end(), 48 double(0)) / u.size(); 49 double var = 0; 50 double skew = 0; 51 double kurtosis = 0; 52 for (int i = 0; i < u.size(); ++i) 53 { 54 double d = (u[i] - mean); 55 double d2 = sqr(d); 56 var += d2; 57 skew += d * d2; 58 kurtosis += d2 * d2; 59 } 60 var /= u.size(); 61 double dev = std::sqrt(var); 62 skew /= u.size() * dev * var; 63 kurtosis /= u.size() * var * var; 64 kurtosis -= 3; 65 double x_mean = ((double)p.a() + p.b()) / 2; 66 double x_var = (sqr((double)p.b() - p.a() + 1) - 1) / 12; 67 double x_skew = 0; 68 double x_kurtosis = -6. * (sqr((double)p.b() - p.a() + 1) + 1) / 69 (5. * (sqr((double)p.b() - p.a() + 1) - 1)); 70 assert(std::abs((mean - x_mean) / x_mean) < 0.01); 71 assert(std::abs((var - x_var) / x_var) < 0.01); 72 assert(std::abs(skew - x_skew) < 0.01); 73 assert(std::abs((kurtosis - x_kurtosis) / x_kurtosis) < 0.01); 74 } 75 } 76