gpt4 book ai didi

c++ - 使用 std::binomial_distribution 在范围之间生成随机数

转载 作者:行者123 更新时间:2023-11-28 04:09:06 25 4
gpt4 key购买 nike

我创建了一个函数来生成稀疏矩阵,但是随机生成器只生成 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

最佳答案

对于 [a, b] 中的数字,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;
}

关于c++ - 使用 std::binomial_distribution 在范围之间生成随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58206187/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com