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 // class bernoulli_distribution 13 14 // template<class _URNG> result_type operator()(_URNG& g); 15 16 #include <random> 17 #include <numeric> 18 #include <vector> 19 #include <cassert> 20 21 template <class T> 22 inline 23 T sqr(T x)24sqr(T x) 25 { 26 return x * x; 27 } 28 main()29int main() 30 { 31 { 32 typedef std::bernoulli_distribution D; 33 typedef std::minstd_rand G; 34 G g; 35 D d(.75); 36 const int N = 100000; 37 std::vector<D::result_type> u; 38 for (int i = 0; i < N; ++i) 39 u.push_back(d(g)); 40 double mean = std::accumulate(u.begin(), u.end(), 41 double(0)) / u.size(); 42 double var = 0; 43 double skew = 0; 44 double kurtosis = 0; 45 for (int i = 0; i < u.size(); ++i) 46 { 47 double d = (u[i] - mean); 48 double d2 = sqr(d); 49 var += d2; 50 skew += d * d2; 51 kurtosis += d2 * d2; 52 } 53 var /= u.size(); 54 double dev = std::sqrt(var); 55 skew /= u.size() * dev * var; 56 kurtosis /= u.size() * var * var; 57 kurtosis -= 3; 58 double x_mean = d.p(); 59 double x_var = d.p()*(1-d.p()); 60 double x_skew = (1 - 2 * d.p())/std::sqrt(x_var); 61 double x_kurtosis = (6 * sqr(d.p()) - 6 * d.p() + 1)/x_var; 62 assert(std::abs((mean - x_mean) / x_mean) < 0.01); 63 assert(std::abs((var - x_var) / x_var) < 0.01); 64 assert(std::abs((skew - x_skew) / x_skew) < 0.01); 65 assert(std::abs((kurtosis - x_kurtosis) / x_kurtosis) < 0.02); 66 } 67 { 68 typedef std::bernoulli_distribution D; 69 typedef std::minstd_rand G; 70 G g; 71 D d(.25); 72 const int N = 100000; 73 std::vector<D::result_type> u; 74 for (int i = 0; i < N; ++i) 75 u.push_back(d(g)); 76 double mean = std::accumulate(u.begin(), u.end(), 77 double(0)) / u.size(); 78 double var = 0; 79 double skew = 0; 80 double kurtosis = 0; 81 for (int i = 0; i < u.size(); ++i) 82 { 83 double d = (u[i] - mean); 84 double d2 = sqr(d); 85 var += d2; 86 skew += d * d2; 87 kurtosis += d2 * d2; 88 } 89 var /= u.size(); 90 double dev = std::sqrt(var); 91 skew /= u.size() * dev * var; 92 kurtosis /= u.size() * var * var; 93 kurtosis -= 3; 94 double x_mean = d.p(); 95 double x_var = d.p()*(1-d.p()); 96 double x_skew = (1 - 2 * d.p())/std::sqrt(x_var); 97 double x_kurtosis = (6 * sqr(d.p()) - 6 * d.p() + 1)/x_var; 98 assert(std::abs((mean - x_mean) / x_mean) < 0.01); 99 assert(std::abs((var - x_var) / x_var) < 0.01); 100 assert(std::abs((skew - x_skew) / x_skew) < 0.01); 101 assert(std::abs((kurtosis - x_kurtosis) / x_kurtosis) < 0.02); 102 } 103 } 104