生成具有均匀分布的随机数(循环获得相同的数) [英] Generate random numbers with uniform distribution (getting same number in loop)
问题描述
我需要在一个均匀分布的循环中的两个指定数字之间生成随机数。我正在使用C ++ 11的 random
库。
I need to generate random numbers between two specified numbers in a loop with a uniform distribution. I am using the random
library of C++11.
我的问题是我不断得到相同的数字在循环。要求在每次循环传递中生成的数字都必须不同。下面的代码:
My problem is that I keep getting the same number in the loop. It is required that the number generated on every loop pass be different. Code below:
#include <cstdlib>
#include <stdio.h>
#include <iostream>
#include <random>
using namespace std;
double randnum (double a, double b)
{
std::default_random_engine generator;
std::uniform_real_distribution<double> distribution (a,b);
double num=distribution(generator);
return num;
}
int main()
{
int np=100;
double umin =0;
double umax=0.5;
double u[np];
for (int i=0;i<np;i++)
{
u[i]=randnum(umin,umax);
cout<<u[i]<<endl;
}
}
请帮助。欢迎通过其他任何方式生成随机数的建议,但必须具有统一的分布。
Please help. Any advice on generating random number by any alternative means is welcome, but it must have a uniform distribution.
推荐答案
随机数引擎标准库中的伪随机即确定内部状态如何初始化和变异的方式。这意味着每个函数调用将获得一个新的新生成器,该生成器将一遍又一遍地继续提供相同的编号。
The random number engines in the Standard Library are pseudo-random, i.e. deterministic in how their internal state is initialized and mutated. This means that each function call will get a fresh new generator that will continue to give the same number over and over again.
只需将生成器
设为 static
函数变量,
Just make the generator
a static
function variable so that its state can evolve over different function calls.
#include <iostream>
#include <random>
using namespace std;
double randnum (double a, double b)
{
static std::default_random_engine generator;
std::uniform_real_distribution<double> distribution (a,b);
return distribution(generator);
}
int main()
{
const int np=100;
double umin =0;
double umax=0.5;
double u[np];
for (int i=0;i<np;i++)
{
u[i]=randnum(umin,umax);
cout<<u[i]<<endl;
}
}
在线示例 。
Live Example.
注意,您将获得编译程序的每次运行都使用相同的数字序列。要获得跨程序调用的更多随机行为,您可以使用例如 std :: random_device
。
Note, you will get the same sequence of numbers for each run of your compiled program. To get more random behavior across program invocations, you can use e.g. std::random_device
.
这篇关于生成具有均匀分布的随机数(循环获得相同的数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!