/*********************************************************************
 * This file is part of the PRAPI library.
 *
 * Copyright (C) 2001 Topi Mäenpää
 * All rights reserved.
 *
 * This program is free software. You can redistribute and/or modify
 * it under the terms of the free software licence found in the
 * accompanying file "COPYING". The licence terms must always be
 * redistributed with this source file. The above copyright notice
 * must be reproduced in all modified and unmodified copies of this
 * source file.
 *
 * $Revision: 1.2 $
 *********************************************************************/

#include "Random.h"

#include <math.h>

namespace prapi
{
	bool Random::_bUseLast = false;

	double Random::gaussian()
	{
		double x1, x2, w, y1;
		static double y2;

		if (_bUseLast)
			{
				y1 = y2;
				_bUseLast = false;
			}
		else
			{
				do
					{
						x1 = 2.0 * drand48() - 1.0;
						x2 = 2.0 * drand48() - 1.0;
						w = x1 * x1 + x2 * x2;
					} while (w >= 1.0);

				w = sqrt((-2.0 * log(w)) / w);
				y1 = x1 * w;
				y2 = x2 * w;
				_bUseLast = true;
			}

		return y1;
	}
}
