@q $Id: random.cweb 1491 2007-12-19 14:36:53Z kamenik $ @>
@q Copyright 2007, Ondra Kamenik @>

@ Start of {\tt random.cpp} file.
@c

#include "random.h"

#include <cstdlib>
#include <limits>
#include <cmath>

@<|RandomGenerator::int_uniform| code@>;
@<|RandomGenerator::normal| code@>;
SystemRandomGenerator system_random_generator;
@<|SystemRandomGenerator::uniform| code@>;
@<|SystemRandomGenerator::initSeed| code@>;

@ 
@<|RandomGenerator::int_uniform| code@>=
int RandomGenerator::int_uniform()
{
	double s = std::numeric_limits<int>::max()*uniform();
	return (int)s;
}

@ This implements Marsaglia Polar Method. 
@<|RandomGenerator::normal| code@>=
double RandomGenerator::normal()
{
	double x1, x2;
	double w;
	do {
		x1 = 2*uniform()-1;
		x2 = 2*uniform()-1;
		w = x1*x1 + x2*x2;
	} while (w >= 1.0 || w < 1.0e-30);
	return x1*std::sqrt((-2.0*std::log(w))/w);
}

@ 
@<|SystemRandomGenerator::uniform| code@>=
double SystemRandomGenerator::uniform()
{
#if !defined(__MINGW32__)
	return drand48();
#else
	return ((double)rand())/RAND_MAX;
#endif
}

@ 
@<|SystemRandomGenerator::initSeed| code@>=
void SystemRandomGenerator::initSeed(int seed)
{
#if !defined(__MINGW32__)
	srand48(seed);
#else
	srand(seed);
#endif
}

@ End of {\tt random.cpp} file.
