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 | // REQUIRES: long_tests |
10 | |
11 | // <random> |
12 | |
13 | // template<class RealType = double> |
14 | // class normal_distribution |
15 | |
16 | // template<class _URNG> result_type operator()(_URNG& g); |
17 | |
18 | #include <random> |
19 | #include <cassert> |
20 | #include <vector> |
21 | #include <numeric> |
22 | #include <cstddef> |
23 | |
24 | #include "test_macros.h" |
25 | |
26 | template <class T> |
27 | inline |
28 | T |
29 | sqr(T x) |
30 | { |
31 | return x * x; |
32 | } |
33 | |
34 | int main(int, char**) |
35 | { |
36 | { |
37 | typedef std::normal_distribution<> D; |
38 | typedef std::minstd_rand G; |
39 | G g; |
40 | D d(5, 4); |
41 | const int N = 1000000; |
42 | std::vector<D::result_type> u; |
43 | for (int i = 0; i < N; ++i) |
44 | u.push_back(d(g)); |
45 | double mean = std::accumulate(u.begin(), u.end(), 0.0) / u.size(); |
46 | double var = 0; |
47 | double skew = 0; |
48 | double kurtosis = 0; |
49 | for (std::size_t i = 0; i < u.size(); ++i) |
50 | { |
51 | double dbl = (u[i] - mean); |
52 | double d2 = sqr(dbl); |
53 | var += d2; |
54 | skew += dbl * d2; |
55 | kurtosis += d2 * d2; |
56 | } |
57 | var /= u.size(); |
58 | double dev = std::sqrt(x: var); |
59 | skew /= u.size() * dev * var; |
60 | kurtosis /= u.size() * var * var; |
61 | kurtosis -= 3; |
62 | double x_mean = d.mean(); |
63 | double x_var = sqr(d.stddev()); |
64 | double x_skew = 0; |
65 | double x_kurtosis = 0; |
66 | assert(std::abs((mean - x_mean) / x_mean) < 0.01); |
67 | assert(std::abs((var - x_var) / x_var) < 0.01); |
68 | assert(std::abs(skew - x_skew) < 0.01); |
69 | assert(std::abs(kurtosis - x_kurtosis) < 0.01); |
70 | } |
71 | |
72 | return 0; |
73 | } |
74 | |