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