#include <stdlib.h>
#include <math.h>

// RANDOM NUMBER GENERATORS

/* rand_uniform: generate a random double between 0.0 (inclusive)
   and 1.0 (exclusive) */

double rand_uniform ()
{
  return (double) random() / ((double) RAND_MAX + 1);
}

/* rand_exp: random number from an exponential distribution
   with the given parameter.  Note: mean = 1/param  */

double rand_exp (double param)
{
  return -log(rand_uniform()) / param;
}

/* rand_normal: generate a random number from a normal distribution
   with mean 0.0 and std 1.0.
   This is gasdev from Numerical Recipes in C */

double rand_normal ()
{
  static int iset = 0;
  static double gset;
  double fac, r, v1, v2;

  // we produce two values each time, so if one is cached,
  // just return it; otherwise, produce two more

  if (iset == 0) {
    do {
      v1 = 2.0 * rand_uniform() - 1.0;
      v2 = 2.0 * rand_uniform() - 1.0;
      r = v1*v1 + v2*v2;
    } while (r >= 1.0);
    fac = sqrt (-2.0 * log (r)/r);
    gset = v1 * fac;
    iset = 1;
    return v2 * fac;
  } else {
    iset = 0;
    return gset;
  }
}

/* rand_lognormal: a random number from a lognormal distribution
   with parameters mu and sigma */

double rand_lognormal (double mu, double sigma)
{
  double x, y;
  x = rand_normal() * sigma + mu;
  y = exp (x);
  return y;
}

/* rand_pareto: a random number from a pareto distribution
   with parameter -1 */

double rand_pareto ()
{
  double x = ((double) random() + 1) / ((double) RAND_MAX + 1);
  return 1.0 / x;
}

