// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
#include <time.h>
#include <math.h>
#ifndef __GNUG__
#define M_PI 3.14159265358979323846
#define PI M_PI
#endif
#include "random.h"

// seed update and random number generation
inline double rangen(int *seed)
{
   *seed=(125*(*seed))%2796203;
   return ((*seed)/2796202.0);
}

// constructor
ransys::ransys()
              {
              int i;
              // use wall-time as start seed
              seed = time(0)%2796203;
              // fill pool with values
              for (i=0;i<101;i++) ran[i] = rangen(&seed);
              }

// global variable used as basis for all random numbers
ransys work;

// uniform distributes random numbers between 0 and 1
double uniform()
{
   int ix;
   double retval;
   ix = rangen(&work.seed)*100;
   retval = work.ran[ix];
   work.ran[ix] = rangen(&work.seed);
   return retval;
}

// standard normal distributed random numbers
double normal()
{
   double h1,h2;
   h1 = sqrt(-2*log(uniform()));
   h2 = 2*PI*uniform();
   return (h1*cos(h2));
}

// generate general normal distributed random numbers
void random(double *z,double m,double sd)
{
   *z = m + sd*normal();
   return;
}
