利用泊松分布实现随机数生成器
不多说,直接上代码,这是在华师大算法课上做的实验代码,C++可运行。
#includeiostream
#includetime.h
#includecmath
using namespace std;
class Random {
Random(bool pseudo = true);
double random_real();
int random_integer(int low, int high);
int poisson(double mean);
void randomByAvg(double avg,int num);
private:
int reseed(); -- Re-randomize the seed.
int seed,multiplier,add_on;
-- constants for use in arithmetic operations
Random::Random(bool pseudo)
Post: The values of seed, add_on, and multiplier are
initialized. The seed is initialized randomly only if pseudo == false.
if (pseudo) seed = 1;
else seed = time(NULL) % INT_MAX;
multiplier = 2743;
add_on = 5923;
int Random::reseed()
Post: The seed is replaced by a pseudorandom successor.
seed = seed * multiplier + add_on;
return seed;
double Random::random_real()
Post: A random real number between 0 and 1 is returned.
double max = INT_MAX + 1.0; --INT_MAX = (2)31 -1
double temp = reseed();
if (temp 0) temp = temp + max;
return temp - max;
int Random::random_integer(int low, int high)
Post: A random integer between low and high is returned. if (low high) return random_integer(high, low);
else return ((int) ((high - low) * random_real())) + low; int Random::poisson(double mean)
Post: A random integer, reflecting a Poisson distribution with parameter mean, is returned.
double limit = exp(-mean);
double product = random_real();
int count = 0;
while (product limit) {
count++;
product *= random_real();
return count;
void Random::randomByAvg(double avg,int num) { double p = 1 - 1.0 - (avg + 1);
int t;double sum=0,ave;
for(int i=0;inum;i++){
t=poisson(avg);
coutt" ";
coutendl;
ave=sum-num*1.0;
cout"随机整数序列的平均值为:"aveendl;
int main(){
cout"请输入概率均值:"endl;
double rand;
cinrand;
cout"请输入随机整数的个数:"endl;
--产生随机序列
Random random;int t;double sum=0;
random.randomByAvg(rand,num);
return 0;
运行结果:
int t; -- t为n最大倍数,且满足 t = m * m
printf ("It is %lf.-n", random ()) ;
std::uniform_real_distributiondouble dis2(0.0, 1.0);
SplittableRandom random = new SplittableRandom();
生成10000个数然后计算分布比例应该可以,只要在90%上下就算通过。
nRF51822_Product Specification_v3.1.pdf中介绍nrf自带真随机生成器:
sum+=Integer.parseInt(list.get(i).get("value").toString());
下面主要介绍的是线性同余法,如C的rand函数和JAVA的java.util.Random类就是使用该方法实现的,其公式为:
code.append(N60_CHARS[i]);
为了生成伪随机数,伪随机数生成器需要称为种子(seed)的信息。
伪随机数的种子是用来对伪随机生成器内部状态进行初始化的。