有时候在进行实验模拟时,需要使用随机数。然而,随机数的设置方法与特点会直接影响实验的效果。
传统随机数生成:
#include<cstdlib>
#include<time.h>
srand(time(NULL));
std::cout << rand() << endl;
建议随机数生成:
#include<random>
std::random_device e;
std::uniform_real_distribution<double> _du(0, 1);
double _drandom = _du(e); //生成0-1的浮点随机数
std::uniform_int_distribution<int> _nu(0, 9999999999);
int _nrandom = _nu(e);//生成0-9999999999的整数随机数
二者区别在于传统方法将时间设置为“种子”(time(NULL)),导致产生的随机数只随时间变化,在同一时间间隔内会生成相同的随机数,因此随机性较差,会直接影响实验中随机性因子的特性。建议的方法可有效规避上述问题。