我的c++随机数不是随机的
my c++ random number is not 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或外部随机数生成器(例如mersenne twister)中标头中的一些随机数。尽管如此,在并行程序中使用随机数并不是一件容易的事。您应该使用专门用于此的随机数生成器(例如r250_omp.h)。
问题可能是由rand
引起的。请参阅此问题的讨论和答案:第一个随机数总是小于其余
似乎生成的相邻种子的数量(您的情况)可能有很大的相关性。rand的实现可能会有所不同,对于某些实现来说,这似乎是一个更加明显的现象。
我认为你的随机生成应该是这样的:
int max=100, min=0;
srand(time(NULL));
int random = (rand() % (max-min)) + min;
相关文章:
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 为什么 Serial.println(<char[]>);返回随机字符?
- 字符串-C++后显示的随机字符
- 循环中的随机函数
- 在c++构造函数中使用随机字符串生成器
- 使用std::mt19937从字符串中返回一个随机单词
- 为什么std::condition_variable notify_all的工作速度比notify_one快(对于随机请
- 如何在C++中高效地构造随机骰子
- 在类中使用随机生成器时出现性能问题
- 在将数字随机生成为数组期间从内存输出随机数的数组
- 将字符随机转换为大写的函数
- 为什么 vector 的随机访问迭代器给出与指针不同的内存地址?
- 如何生成一个随机的 n 位数,其中 n 是任意的
- 将随机生成的数字添加到数组 + 对这些数组求平均值
- 如何使用要传递给 mt19937 的可选随机种子参数设计函数
- 在C++中随机生成 20 个非重复数字
- GCC:随机构建导致执行期间分段错误
- 如何使用 SML 随机生成八进制元组
- 当我尝试使用它时,Scanf 会抛出一个随机异常(scanf_s 也是如此)
- 将正态随机变量与任意 RHO(corrcoef) 相关联