[英]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
我很困惑....有什么幫助嗎? 謝謝。
You Problem是cstdlib的rand()函數。 它不是一個好的隨機數發生器。 如果你想在c ++中使用適當的隨機數,可以使用c ++ - 11或外部隨機數生成器(例如mersenne twister)中的一些。 但是,在並行程序中使用隨機數並非易事。 您應該使用隨機數生成器,它們是專門的(例如r250_omp.h)。
問題很可能是你的rand
造成的。 請參閱此問題的討論和答案: 第一個隨機數總是小於休息
似乎相鄰種子(您的情況)生成的數字可能非常相關。 蘭德的實現可能會有所不同,對於某些實現,它似乎是一個更加明顯的現象。
我認為你的隨機類應該是這樣的:
int max=100, min=0;
srand(time(NULL));
int random = (rand() % (max-min)) + min;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.