Generating a random number

B. Banerjee bbanerje at sjuvax.UUCP
Thu Dec 20 14:56:35 AEST 1984

>> I am in need of a workable function that will generate a random number
>> for me.  The only restriction (and this is a tight one, I'll admit) is
>> that it be portable (i.e.  it can't make any system callsNo system
>> clock is available.  Thanks.
>> ]ohn [ooper

Well, I do have a TRUE random number generator that is machine
independent You have these 32 boxes containing cats.  The lid of the
box is wired so that when opened, the wire will go high (1) if the cat
is alive, and low (0) if the cat is dead...

Seriously, the following algorithm appeared in "Pascal News", June
1978.  I cribbed it, and translated it into C.  References given in the
magazine were (I haven't verified this)

1. Whittlesey, J. R. B. "A Comparison of the Correlational Behaviour of
Random Number Generators for the IBM 360". CACM Sept. 1968

2. Lewis, T. G. "Distribution Sampling for Computer Simulation." D. C.
Heath and Co. (1975).

It uses the "Feedback shift register method" (whatever that is).  It
was defined for 16 bit integers.  Changing it for different size
integers requires changing the constants BIG, LEFT_SHIFT and
RIGHT_SHIFT.  As I am not sure how LEFT_SHIFT and RIGHT_SHIFT change
with word size, but it is supposedly explained in (2) ) so I left the
declaration as a short.  Oh yes, the original algorithm that I cribbed
this from was written by Brian Meekings, University of Lancaster.

Seed should be a positive NON ZERO short integer.  Result will be a
random float in the interval [0,1].

Enough Blather... Here it is.

# include <stdio.h>

/* The following constants are correct for 16 bit integers */

# define LEFT_SHIFT 4	/* This and the next value are voodoo to me */
# define RIGHT_SHIFT 11

# define BIG	32767	/* largest 16 bit integer	*/

float random(seed)
short *seed;
	*seed ^= (*seed << LEFT_SHIFT);
	*seed ^= (*seed >> RIGHT_SHIFT);


Have fun!


				Binayak Banerjee
		{allegra | astrovax | bpa | burdvax}!sjuvax!bbanerje
	Send Flames, I love mail.

More information about the Comp.lang.c mailing list