rand32類

寫的一個簡單的rand32類。線性同餘法生成。

附源碼:

rand32.h

//**************************************************************
//desc:generate pseudo random numbers through Linear Congruence
//name:rand32.h
//auth:zhouping
//date:20140102
//**************************************************************

#ifndef RAND32_H
#define RAND32_H

class rand32
{
public:
	rand32();
	~rand32();

	//initialize the seed
	void init_seed(unsigned int seed);

	//generate a nonnegative integer range of [0, 2^32)
	unsigned int rand();

    //generate an integer range of [min, max)
	int rand(int min, int max);

private:
	unsigned int rand_num;
};

#endif //~RAND32_H

rand32.cpp

//******************************************************************************
//desc:generate pseudo random numbers through Linear Congruence Method
//name:rand32.cpp
//auth:zhouping
//date:20140102
//******************************************************************************

#include "rand32.h"

rand32::rand32()
{
	init_seed(1);
}

rand32::~rand32()
{
}

//initialize the seed
void rand32:: init_seed(unsigned int seed)
{
	rand_num = seed;
}

//generate a nonnegative integer range of [0, 2^32)
unsigned int rand32::rand()
{
	rand_num = 214013 * rand_num + 2531011;
	return rand_num;
}

//generate an integer range of [min, max)
int rand32::rand(int min, int max)
{
	return min + rand() % (max - min);
}

 參考:http://www.zhihu.com/question/22818104

点赞