C++,mpi:创建随机数据的最简单方法

C++ ,mpi : easiest way to create random data

在我的 c++ mpi 项目中,我创建了函数:

 RandomDataInitialization(pMatrix, pVector, Size);

我正在尝试在函数 RandomDataInitialization 中形成矩阵 A 和向量 b 的值。所以我想问问也许有人知道最简单和最有效的方法吗?

一般。

c++标准随机函数的工作方式如下:

  1. 创建一个伪随机引擎。
  2. 用随机种子初始化它(一个很好的来源是 std::random_device)
  3. 创建分发对象(例如uniform_int_distribution或uniform_real_distribution)
  4. 通过分发对象传递生成的伪随机数(由引擎生成)以给出随机数。

例如,要随机化数组或向量(矩阵的可能存储机制):

#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);
                  });
}