/* -*-C-*- dran.c */

#include "elefunt.h"

/***********************************************************************
Random number generator - based on Algorithm 266 by Pike and Hill
(modified by Hansson), Communications of the ACM, Vol. 8, No. 10,
October 1965.

This subprogram is intended for use on computers with fixed point
wordlength of at least 29 bits.  It is best if the floating point
significand has at most 29 bits.
***********************************************************************/

#define TWOP29	536870912.0e+00L			/* 2^29 */
#define TWOP58	288230376151711744.0e+00L		/* 2^(2*29) */
#define TWOP87	154742504910672534362390528.0e+00L	/* 2^(3*29) */

#define DEFAULT_INITIAL_SEED	100001L

static long iy = DEFAULT_INITIAL_SEED;

#if STDC
long
(qranset)(long seed)
#else
long
(qranset)(seed)
long seed;
#endif
{
    long old_seed;

    old_seed = iy;
    if (seed < 0)
	seed = -seed;
    if (seed < 0)			/* then had seed = LONG_MIN  */
        seed = LONG_MAX;
    iy = (seed == 0) ? DEFAULT_INITIAL_SEED : seed;

    /* Guard against bad DEFAULT_INITIAL_SEED */
    if (iy < 0)
	iy = -iy;
    if (iy < 0)
	iy = LONG_MAX;

    /* Ensure that (iy * 125) is positive (i.e., does not overflow) */
    if (iy > (LONG_MAX / 125))		/* see below for magic constant 125 */
	iy = (LONG_MAX / 125);

    return (old_seed);
}


qp_t
(qran)(VOID_ARG)
{
    qp_t result;

    iy = iy * 125;
    iy = iy - (iy / 2796203L) * 2796203L;
    result = ((qp_t) (iy)) / 2796203.0e+00L;

    iy = iy * 125;
    iy = iy - (iy / 2796203L) * 2796203L;
    result += (((qp_t) (iy)) / 2796203.0e+00L) / TWOP29;

    iy = iy * 125;
    iy = iy - (iy / 2796203L) * 2796203L;
    result += (((qp_t) (iy)) / 2796203.0e+00L) / TWOP58;

    iy = iy * 125;
    iy = iy - (iy / 2796203L) * 2796203L;
    result += (((qp_t) (iy)) / 2796203.0e+00L) / TWOP87;

    return (result);
}
