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

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

本文关键字:数据 最简单 方法 随机 创建 mpi C++      更新时间:2023-10-16

在我的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);
                  });
}