/* -*-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 DEFAULT_INITIAL_SEED	100001L

static long iy = DEFAULT_INITIAL_SEED;

#if STDC
long
(ranset)(long seed)
#else
long
(ranset)(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);
}


dp_t
(ran)(VOID_ARG)
{
    dp_t result;

    iy = iy * 125;
    iy = iy - (iy / 2796203L) * 2796203L;
    result = ((dp_t) (iy)) / 2796203.0e0;

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

    return (result);
}
