使用std :: binomial_distribution

时间:2019-10-02 17:10:41

标签: c++ random sparse-matrix

我创建了一个生成稀疏矩阵的函数,但是随机生成器仅生成 1s 的值,我需要使其生成特定范围内的数字。

size_t spare_matrix_generator(int *M, size_t rows, size_t cols)
{
    std::random_device rd;
    std::mt19937 gen(rd());
    gen.seed(time(NULL));

    std::binomial_distribution<int> distribution(1, 0.5);

    size_t NNZ = 0;

    for (szie_t i = 0; i < rows*cols; i++)
    {
        M[i] = distribution(gen);
        std::cout << M[i] << " ";
        if (A[i] != 0)
            NNZ++;
    }
    std::cout << std::endl;

    return NNZ;
}

假设 5x5 矩阵,上述函数的示例输出如下:

0 1 1 0 0 
1 0 0 0 1
0 0 0 1 0
1 0 0 0 1
0 0 0 0 1

1 个答案:

答案 0 :(得分:1)

对于[a,b]中带有std::binomial_distribution在0到b-a之间的随机数,并将a添加到生成的结果符合输入范围[a,b]:

size_t spare_matrix_generator(int *M, size_t rows, size_t cols)
{
    std::random_device rd;
    std::mt19937 gen(rd());
    gen.seed(time(NULL));
    int b = 12, a = 3;

    std::binomial_distribution<int> distribution(b-a, 0.5);

    // To handle matrix sparsity
    float zero_prob = 0.8;
    std::mt19937 sparse_gen(rd() + 42);
    std::uniform_real_distribution<double> sparse_dist(0.0,1.0);

    size_t NNZ = 0;

    for (szie_t i = 0; i < rows*cols; i++)
    {
        if(sparse_dist(sparse_gen) > zero_prob){
            M[i] = a + distribution(gen);
        } else {
            M[i] = 0;
        }

        std::cout << M[i] << " ";
        if (M[i] != 0)
            NNZ++;
    }
    std::cout << std::endl;

    return NNZ;
}