blob: fe704228e7889111e06836b92f83d483ebedd667 [file] [log] [blame]
Howard Hinnant54305402010-05-25 00:27:34 +00001//===----------------------------------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Howard Hinnantb64f8b02010-11-16 22:09:02 +00005// This file is dual licensed under the MIT and the University of Illinois Open
6// Source Licenses. See LICENSE.TXT for details.
Howard Hinnant54305402010-05-25 00:27:34 +00007//
8//===----------------------------------------------------------------------===//
Jonathan Roelofsd9144e82014-12-11 18:35:36 +00009//
10// REQUIRES: long_tests
Howard Hinnant54305402010-05-25 00:27:34 +000011
12// <random>
13
14// template<class RealType = double>
15// class piecewise_linear_distribution
16
17// template<class _URNG> result_type operator()(_URNG& g, const param_type& parm);
18
19#include <random>
20#include <vector>
21#include <iterator>
22#include <numeric>
Howard Hinnant54305402010-05-25 00:27:34 +000023#include <cassert>
24
25template <class T>
26inline
27T
28sqr(T x)
29{
30 return x*x;
31}
32
33double
34f(double x, double a, double m, double b, double c)
35{
36 return a + m*(sqr(x) - sqr(b))/2 + c*(x-b);
37}
38
39int main()
40{
41 {
42 typedef std::piecewise_linear_distribution<> D;
43 typedef D::param_type P;
44 typedef std::mt19937_64 G;
45 G g;
46 double b[] = {10, 14, 16, 17};
47 double p[] = {25, 62.5, 12.5, 0};
48 const size_t Np = sizeof(p) / sizeof(p[0]) - 1;
49 D d;
50 P pa(b, b+Np+1, p);
51 const int N = 1000000;
52 std::vector<D::result_type> u;
53 for (int i = 0; i < N; ++i)
54 {
55 D::result_type v = d(g, pa);
56 assert(10 <= v && v < 17);
57 u.push_back(v);
58 }
59 std::sort(u.begin(), u.end());
60 int kp = -1;
Dan Albert1d4a1ed2016-05-25 22:36:09 -070061 double a;
62 double m;
63 double bk;
64 double c;
Howard Hinnant54305402010-05-25 00:27:34 +000065 std::vector<double> areas(Np);
66 double S = 0;
67 for (int i = 0; i < areas.size(); ++i)
68 {
69 areas[i] = (p[i]+p[i+1])*(b[i+1]-b[i])/2;
70 S += areas[i];
71 }
72 for (int i = 0; i < areas.size(); ++i)
73 areas[i] /= S;
74 for (int i = 0; i < Np+1; ++i)
75 p[i] /= S;
76 for (int i = 0; i < N; ++i)
77 {
78 int k = std::lower_bound(b, b+Np+1, u[i]) - b - 1;
79 if (k != kp)
80 {
81 a = 0;
82 for (int j = 0; j < k; ++j)
83 a += areas[j];
84 m = (p[k+1] - p[k]) / (b[k+1] - b[k]);
85 bk = b[k];
86 c = (b[k+1]*p[k] - b[k]*p[k+1]) / (b[k+1] - b[k]);
87 kp = k;
88 }
89 assert(std::abs(f(u[i], a, m, bk, c) - double(i)/N) < .001);
90 }
91 }
92}