在我的 C++ mpi 项目中,我创建了函数:
RandomDataInitialization(pMatrix, pVector, Size);
我正在尝试在函数 RandomDataInitialization 中形成矩阵 A 和 vector b 的值。所以我想问问也许有人知道最简单和最有效的方法吗?
最佳答案
一般。
c++标准随机函数的工作方式如下:
- 创建一个伪随机引擎。
- 用随机种子初始化它(一个很好的来源是 std::random_device)
- 创建分布对象(例如 uniform_int_distribution 或 uniform_real_distribution)
- 将生成的伪随机数(由引擎生成)通过分布对象传递给随机数。
例如,随机化一个数组或 vector (矩阵的可能存储机制):
#include <random>
#include <array>
#include <algorithm>
int main()
{
// a 3x3 matrix of doubles
std::array<double, 9> matrix_data;
// make an instance of a random device to generate one real random number
// this is "slow" so we do it as little as possible.
std::random_device rd {};
// create the random engine and seed it from the random device
auto engine = std::default_random_engine(rd());
// create a uniform distribution generator which gives values in the range
// 0.0 to 1.0
auto distribution = std::uniform_real_distribution<double>(0, 1.0);
// generate the random data by passing random numbers generated by the
// engine through the distribution object.
std::generate(std::begin(matrix_data), std::end(matrix_data),
[&distribution, &engine]
{
return distribution(engine);
});
}
关于C++,mpi : easiest way to create random data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36374382/