c++ - 我的 C++ 随机数不是随机的

标签 c++ random

我正在运行这个

#include <boost/mpi.hpp>
#include <iostream>
#include <vector>
#include <cstdlib>
#include <time.h>
namespace mpi = boost::mpi;

int main()
{
    mpi::environment env;
    mpi::communicator world;



    srand (time(NULL));
    std::srand(time(0) + world.rank());
    int my_number = std::rand();
    if (world.rank() == 0) {
        std::vector<int> all_numbers;
        gather(world, my_number, all_numbers, 0);
        for (int proc = 0; proc < world.size(); ++proc)
            std::cout << "Process #" << proc << " thought of "
            << all_numbers[proc] << std::endl;
    } else {
        gather(world, my_number, 0);
    }

    return 0;
}

然而,为了分布式生成随机数,它每次都会给我大约相同数量级的数字......

dhcp-18-189-66-216:ising2 myname$ make
mpic++ -I/usr/local/include/boost -L/usr/local/lib -lboost_mpi -lboost_serialization main.cpp -o main
mpirun -n 4 main
Process #0 thought of 238772362
Process #1 thought of 238789169
Process #2 thought of 238805976
Process #3 thought of 238822783
dhcp-18-189-66-216:ising2 myname$ make
mpic++ -I/usr/local/include/boost -L/usr/local/lib -lboost_mpi -lboost_serialization main.cpp -o main
mpirun -n 4 main
Process #0 thought of 238805976
Process #1 thought of 238822783
Process #2 thought of 238839590
Process #3 thought of 238856397
dhcp-18-189-66-216:ising2 myname$ make
mpic++ -I/usr/local/include/boost -L/usr/local/lib -lboost_mpi -lboost_serialization main.cpp -o main
mpirun -n 4 main
Process #0 thought of 238856397
Process #1 thought of 238873204
Process #2 thought of 238890011
Process #3 thought of 238906818
dhcp-18-189-66-216:ising2 myname$ 

在网站 http://www.boost.org/doc/libs/1_55_0/doc/html/mpi/tutorial.html 中,其他人说他们得到:

Process #0 thought of 332199874
Process #1 thought of 20145617
Process #2 thought of 1862420122
Process #3 thought of 480422940
Process #4 thought of 1253380219
Process #5 thought of 949458815
Process #6 thought of 650073868

我很困惑....有什么帮助吗?谢谢。

最佳答案

您的问题是 cstdlib 的 rand() 函数。它不是一个好的随机数生成器。如果您想在 C++ 中使用适当的随机数,请使用 C++11 header 中的一些随机数或外部随机数生成器(例如 mersenne twister)。 但是尽管如此,在并行程序中使用随机数并不是一件容易的事。您应该使用专门用于此的随机数生成器(例如 r250_omp.h)。

关于c++ - 我的 C++ 随机数不是随机的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31031797/

相关文章:

c++ - 将 const unsigned long 流式传输到 fstream

c++ - 生成随机二维数组

c# - 为什么这个 Base36 随机字符串不使用 RandomNumberGenerator 随机分布字符

c++ - 新与新(以 malloc 为特色!)

c# - Random().Next() 流需要多长时间才能重复?

python:当您使用random.choice(seq)从序列中随机选择一个元素时如何知道索引

android - 关于 Firestore 中查询的随机结果

C++创建一个函数的 friend ?

c++ - 在 C++ 中声明一个 const 对象需要一个用户定义的默认构造函数。如果我有一个可变成员变量,为什么不呢?

c++ - 无法理解类型别名和常量