是否有在 c++ 中使用三角分布生成随机数的函数

Is there a function to generate random number using triangular distribution in c++?

本文关键字:分布 随机数 函数 三角 c++ 是否      更新时间:2023-10-16

我正在 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。