我试图从实数中的[0,1)的范围内的均匀分布生成数。 但是编译器产生,其是从[0,1)的范围内的数字。
下面是代码:
int main(void) {
// Solver solve;
mt19937 mteng;
mteng.seed(rdtsc());
uniform_real<double> uniRealD;
double randomNum;
for (int index = 0; index < 10; index++){
randomNum = uniRealD(mteng);
if(randomNum<0.5)
cout<<index<<" no. random number is: "<<randomNum<<endl;
else
cout<<"number generate is not in range"<<endl;
}
return 0;
}
什么任何意见可能是错误的代码? 我使用rdtsc()
作为种子。
我必须摆脱你的种子功能, rdtsc()
使一些包括引入using namespace std
,并更改为0.5至1.0,并改变uniform_real
到uniform_real_distribution
,但在那之后,使用的libc ++,我得到:
#include <random>
#include <iostream>
using namespace std;
int main(void) {
// Solver solve;
mt19937 mteng;
mteng.seed(0);
uniform_real_distribution<double> uniRealD;
double randomNum;
for (int index = 0; index < 10; index++){
randomNum = uniRealD(mteng);
if(randomNum<1.0)
cout<<index<<" no. random number is: "<<randomNum<<endl;
else
cout<<"number generate is not in range"<<endl;
}
return 0;
}
0 no. random number is: 0.592845
1 no. random number is: 0.844266
2 no. random number is: 0.857946
3 no. random number is: 0.847252
4 no. random number is: 0.623564
5 no. random number is: 0.384382
6 no. random number is: 0.297535
7 no. random number is: 0.056713
8 no. random number is: 0.272656
9 no. random number is: 0.477665
您的代码不应该这样做。 大概是在实现中的错误。 什么编译器和库版本? 尝试移动从TR1客场C ++ 11。
if(randomNum<0.5)
cout<<index<<" no. random number is: "<<randomNum<<endl;
else
cout<<"number generate is not in range"<<endl;
更改if
语句if(randomNum < 1.)