/*
    libmaus2
    Copyright (C) 2015 German Tischler

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#if ! defined(LIBMAUS2_RANDOM_GAUSSIANRANDOM_HPP)
#define LIBMAUS2_RANDOM_GAUSSIANRANDOM_HPP

#include <libmaus2/random/UniformUnitRandom.hpp>
#include <cmath>

#if ! defined(M_PI)
#define M_PI 3.14159265358979323846
#endif

namespace libmaus2
{
	namespace random
	{
		struct GaussianRandom
		{
			/* density function of normal distribution */
			static double gaussian(double const x, double const sigma, double const mu)
			{
				return 1.0 / sqrt(2*M_PI*sigma*sigma) * ::exp ( - (x-mu)*(x-mu) / (2.0*sigma*sigma));
			}

			static double erf(double z)
			{
				if ( z >= 0 )
					return ::std::erf(z);
				else
					return -erf(-z);
			}

			/* probability function of normal distribution (integral over density) */
			static double probability(double const x, double const sigma, double const mu)
			{
				if ( x >= mu )
					return 0.5*(1.0+GaussianRandom::erf((x-mu)/(std::sqrt(2*sigma*sigma)) ));
				else
					return 1 - 0.5*(1.0+GaussianRandom::erf((mu-x)/(std::sqrt(2*sigma*sigma)) ));
			}

			/*
			 * search for (approximation of) smallest value v such that probability(v,sigma,mu) >= t
			 */
			static double search(double const t, double const sigma, double const mu)
			{
				double low = mu - 10*sigma, high = mu + 10*sigma;

				while ( high - low > 1e-6 )
				{
					double const mid = (high+low)/2.0;
					double const v = probability(mid,sigma,mu);

					if ( v < t )
						low = mid;
					else
						high = mid;
				}

				return low;
			}


			/* produce random number from Gaussian distribution */
			static double random(double const sigma, double const mu)
			{
				return search(UniformUnitRandom::uniformUnitRandom(),sigma,mu);
			}
		};
	}
}
#endif
