random.cpp

来自「包括图、二叉树、链表」· C++ 代码 · 共 53 行

CPP
53
字号
#include "Random.h"
#include <limits.h>
#include <time.h>
#include <math.h>

int Random::reseed()
//Post:The seed is replaced by a psuedorandom successor
{
	seed=seed*multiplier+add_on;
	return seed;
}

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=static_cast<int>(time(NULL)%INT_MAX);
		multiplier=2743;
		add_on=5923;
	}
}

double Random::random_real()
{
	/*Post:A random real number between 0 and 1 is returned*/
	double max=INT_MAX+1.0;
	double temp=reseed();
	if (temp<0)
	{
		temp=temp+max;
	}
	return temp/max;
}

int Random::poisson(double mean)
{
	/*Post:A random integer, reflecting a Poisson distribution with parameter mean, is return.*/
	double limit=exp(-mean);
	double product=random_real();
	int count=0;
	while (product>limit)
	{
		count++;
		product*=random_real();
	}
	return count;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?