[英]Is there a function to generate random number using triangular distribution in c++?
我在 c++ 中搜索一个函数,我给它( min, mode, max )然后它返回一个由三角分布生成的随机数。 如果有实现这个功能的代码就好了。
std::piecewise_linear_distribution
可用于模拟三角分布。
下面是一个基于链接的 cppreference 页面上的示例代码的示例,它生成一个三角形分布,该分布生成 0 到 30 之间的数字,峰值为 20:
#include <random>
#include <iostream>
#include <iomanip>
#include <array>
#include <map>
std::piecewise_linear_distribution<double> triangular_distribution(double min, double peak, double max)
{
std::array<double, 3> i{min, peak, max};
std::array<double, 3> w{0, 1, 0};
return std::piecewise_linear_distribution<double>{i.begin(), i.end(), w.begin()};
}
int main() {
std::random_device rd;
// create a mersenne twister PRNG seeded from some implementation-defined random source
std::mt19937 gen(rd());
// create a triangular distribution with a minimum of 0, a peak at 20, and a maximum of 30
auto dist = triangular_distribution(0, 20, 30);
std::map<int, int> hist;
// use our distribution to generate 10,000 random numbers
// (truncated to integers for the sake of output; the generated numbers are actually real numbers)
for (int i = 0; i < 10000; ++i) {
double num = dist(gen);
++hist[num];
}
// print out a nice histogram of the numbers generated
for(auto p : hist) {
std::cout << std::setw(2) << std::setfill('0') << p.first << ' '
<< std::string(p.second/10,'*') << '\n';
}
}
可能的输出:
00 **
01 *****
02 ******
03 ************
04 **************
05 ******************
06 **********************
07 *************************
08 **************************
09 *********************************
10 ************************************
11 **************************************
12 *************************************
13 ********************************************
14 **************************************************
15 **************************************************
16 *******************************************************
17 *******************************************************
18 ************************************************************
19 *****************************************************************
20 **************************************************************
21 *******************************************************
22 ************************************************
23 *******************************************
24 ***************************************
25 ******************************
26 **************************
27 ****************
28 ***********
29 ***
您可以通过对两个制服U₁和U₂求和来从简单的三角形分布T中采样。 在 C 术语中,这将是:
float U1 = (float)rand() / RAND_MAX;
float U2 = (float)rand() / RAND_MAX;
float T = U1 + U2;
相应地缩放:结果在 0 和 2 之间,模式为 1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.