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

2019-07-28 10:24发布

In my c++ mpi project i created function:

 RandomDataInitialization(pMatrix, pVector, Size);

and I am trying to form the values for matrix A and vector b in function RandomDataInitialization. So i want to ask maybe someone knows the easiest and most effective way to do this ?

标签: c++ mpi
1条回答
走好不送
2楼-- · 2019-07-28 11:08

In general.

The way c++ standard random functions work is as follows:

  1. create a pseudo random engine.
  2. initialise it with a random seed (a good source of this being the std::random_device)
  3. create a distribution object (such as uniform_int_distribution or uniform_real_distribution)
  4. pass generated pseudo-random numbers (generated by the engine) through the distribution object to give random numbers.

For example, to randomise an array or vector (a likely storage mechanism for your matrix):

#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);
                  });
}
查看更多
登录 后发表回答