1 //===----------------------------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 // <random> 10 11 // class bernoulli_distribution 12 13 // template<class _URNG> result_type operator()(_URNG& g); 14 15 #include <random> 16 #include <numeric> 17 #include <vector> 18 #include <cassert> 19 #include <cstddef> 20 21 #include "test_macros.h" 22 23 template <class T> 24 inline 25 T sqr(T x)26sqr(T x) 27 { 28 return x * x; 29 } 30 main(int,char **)31int main(int, char**) 32 { 33 { 34 typedef std::bernoulli_distribution D; 35 typedef std::minstd_rand G; 36 G g; 37 D d(.75); 38 const int N = 100000; 39 std::vector<D::result_type> u; 40 for (int i = 0; i < N; ++i) 41 u.push_back(d(g)); 42 double mean = std::accumulate(u.begin(), u.end(), 43 double(0)) / u.size(); 44 double var = 0; 45 double skew = 0; 46 double kurtosis = 0; 47 for (std::size_t i = 0; i < u.size(); ++i) 48 { 49 double dbl = (u[i] - mean); 50 double d2 = sqr(dbl); 51 var += d2; 52 skew += dbl * d2; 53 kurtosis += d2 * d2; 54 } 55 var /= u.size(); 56 double dev = std::sqrt(var); 57 skew /= u.size() * dev * var; 58 kurtosis /= u.size() * var * var; 59 kurtosis -= 3; 60 double x_mean = d.p(); 61 double x_var = d.p()*(1-d.p()); 62 double x_skew = (1 - 2 * d.p())/std::sqrt(x_var); 63 double x_kurtosis = (6 * sqr(d.p()) - 6 * d.p() + 1)/x_var; 64 assert(std::abs((mean - x_mean) / x_mean) < 0.01); 65 assert(std::abs((var - x_var) / x_var) < 0.01); 66 assert(std::abs((skew - x_skew) / x_skew) < 0.01); 67 assert(std::abs((kurtosis - x_kurtosis) / x_kurtosis) < 0.02); 68 } 69 { 70 typedef std::bernoulli_distribution D; 71 typedef std::minstd_rand G; 72 G g; 73 D d(.25); 74 const int N = 100000; 75 std::vector<D::result_type> u; 76 for (int i = 0; i < N; ++i) 77 u.push_back(d(g)); 78 double mean = std::accumulate(u.begin(), u.end(), 79 double(0)) / u.size(); 80 double var = 0; 81 double skew = 0; 82 double kurtosis = 0; 83 for (std::size_t i = 0; i < u.size(); ++i) 84 { 85 double dbl = (u[i] - mean); 86 double d2 = sqr(dbl); 87 var += d2; 88 skew += dbl * d2; 89 kurtosis += d2 * d2; 90 } 91 var /= u.size(); 92 double dev = std::sqrt(var); 93 skew /= u.size() * dev * var; 94 kurtosis /= u.size() * var * var; 95 kurtosis -= 3; 96 double x_mean = d.p(); 97 double x_var = d.p()*(1-d.p()); 98 double x_skew = (1 - 2 * d.p())/std::sqrt(x_var); 99 double x_kurtosis = (6 * sqr(d.p()) - 6 * d.p() + 1)/x_var; 100 assert(std::abs((mean - x_mean) / x_mean) < 0.01); 101 assert(std::abs((var - x_var) / x_var) < 0.01); 102 assert(std::abs((skew - x_skew) / x_skew) < 0.01); 103 assert(std::abs((kurtosis - x_kurtosis) / x_kurtosis) < 0.02); 104 } 105 106 return 0; 107 } 108