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