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 piecewise_linear_distribution 15 16 // template<class _URNG> result_type operator()(_URNG& g, const param_type& parm); 17 18 #include <algorithm> // for sort 19 #include <cassert> 20 #include <cmath> 21 #include <cstddef> 22 #include <limits> 23 #include <random> 24 #include <vector> 25 26 #include "test_macros.h" 27 28 template <class T> 29 inline 30 T 31 sqr(T x) 32 { 33 return x*x; 34 } 35 36 double 37 f(double x, double a, double m, double b, double c) 38 { 39 return a + m*(sqr(x) - sqr(b))/2 + c*(x-b); 40 } 41 42 int main(int, char**) 43 { 44 { 45 typedef std::piecewise_linear_distribution<> D; 46 typedef D::param_type P; 47 typedef std::mt19937_64 G; 48 G g; 49 double b[] = {10, 14, 16, 17}; 50 double p[] = {25, 62.5, 12.5, 0}; 51 const std::size_t Np = sizeof(p) / sizeof(p[0]) - 1; 52 D d; 53 P pa(b, b+Np+1, p); 54 const std::size_t N = 1000000; 55 std::vector<D::result_type> u; 56 for (std::size_t i = 0; i < N; ++i) 57 { 58 D::result_type v = d(g, pa); 59 assert(10 <= v && v < 17); 60 u.push_back(v); 61 } 62 std::sort(u.begin(), u.end()); 63 std::ptrdiff_t kp = -1; 64 double a = std::numeric_limits<double>::quiet_NaN(); 65 double m = std::numeric_limits<double>::quiet_NaN(); 66 double bk = std::numeric_limits<double>::quiet_NaN(); 67 double c = std::numeric_limits<double>::quiet_NaN(); 68 std::vector<double> areas(Np); 69 double S = 0; 70 for (std::size_t i = 0; i < areas.size(); ++i) 71 { 72 areas[i] = (p[i]+p[i+1])*(b[i+1]-b[i])/2; 73 S += areas[i]; 74 } 75 for (std::size_t i = 0; i < areas.size(); ++i) 76 areas[i] /= S; 77 for (std::size_t i = 0; i < Np+1; ++i) 78 p[i] /= S; 79 for (std::size_t i = 0; i < N; ++i) 80 { 81 std::ptrdiff_t k = std::lower_bound(b, b + Np + 1, u[i]) - b - 1; 82 if (k != kp) { 83 a = 0; 84 for (int j = 0; j < k; ++j) 85 a += areas[j]; 86 m = (p[k + 1] - p[k]) / (b[k + 1] - b[k]); 87 bk = b[k]; 88 c = (b[k + 1] * p[k] - b[k] * p[k + 1]) / (b[k + 1] - b[k]); 89 kp = k; 90 } 91 assert(std::abs(f(u[i], a, m, bk, c) - double(i) / N) < .0013); 92 } 93 } 94 95 return 0; 96 } 97