//---------------------------------------------------------------------------
//============================================================================
// Name : Random.cpp
// Author : Shao Zongru (Doris South)
// Version :
// Copyright : The copy right belongs to Shao Zongru (Doris South)
// Description : random number generator
// state
// uniformInt, uniform, normal
//============================================================================
#include <cmath>
#include <math.h>
#include <stdlib.h>
#include <windows.h>
#include <exception>
#include <iostream>
using namespace std;
#include "Random.h"
//---------------------------------------------------------------------------
const double PI = 3.14159265358979323846;
//
const int Random::A = 48271;
const int Random::M = 2147483647;
const int Random::Q = M / A;
const int Random::R = M % A;
Random::Random() {
//Random::Random
// get time as the seed
state = (unsigned int) GetTickCount();
//
}
Random::Random(int initVal) :
state(initVal) {
//Random::Random
//
}
Random::~Random() {
//Random::~Random
//
}
void Random::setState(int initVal) {
//Random::setState
try {
state = initVal;
} catch (exception& e) {
cout << e.what() << endl;
}
//
}
int Random::uniformInt() {
//Random::uniform
try {
return randomInt();
} catch (exception& e) {
cout << e.what() << endl;
}
//
}
int Random::uniformInt(int min, int max) {
//Random::uniform
try {
int n = max - min + 1;
int r = this->randomInt();
r %= n;
r += min;
return r;
} catch (exception& e) {
cout << e.what() << endl;
}
//
}
bool Random::randomBool(double p) {
//Random::randomBool
try {
double d = uniform(0.0, 1.0);
return (d < p);
} catch (exception& e) {
cout << e.what() << endl;
}
//
}
double Random::uniform(double min, double max) {
//Random::uniform
try {
int i = randomInt();
srand(i);
return min + (max - min) * ((double) rand() / (double) RAND_MAX);
} catch (exception& e) {
cout << e.what() << endl;
}
//
}
double Random::normal(double miu, double gama) {
//Random::normal
try {
double u1 = uniform();
if (u1 == 0.0) {
u1 = 0.0000001;
}
double u2 = uniform();
return miu + gama * sqrt(-2 * log(u1)) * cos(2 * PI * u2);
} catch (exception& e) {
cout << e.what() << endl;
}
//
}
int Random::randomInt() {
//Random::randomInt
try {
int tmpState = A * (state % Q) - R * (state / Q);
//
if (tmpState >= 0)
state = tmpState;
else
state = tmpState + M;
//
return state;
} catch (exception& e) {
cout << e.what() << endl;
}
//
}