[comp.lang.c] How do I get random #s?

tsource@dhw68k.cts.com (Aryeh Friedman) (02/01/89)

	I am new to C and I want to know how to get random numbers returned.


-- 
Aryeh Friedman (aka The source)
tsource@dhw68k.cts.COM or tsource@dhw68k.UUCP

thomas@infmx.UUCP (Thomas Rush) (02/03/89)

In article <19415@dhw68k.cts.com>, (Aryeh Friedman) writes:
> 
> 	I am new to C and I want to know how to get random numbers returned.

	Take them back to the store with the original receipt and packing
materials.  What?  You didn't keep the receipt?

g thomas rush		|Of course my opinions are important!  After all, I
Informix Software	|don't just _work_ here.... sometimes I play games.

gwyn@smoke.BRL.MIL (Doug Gwyn ) (02/03/89)

In article <19415@dhw68k.cts.com> tsource@dhw68k.cts.com (Aryeh Friedman) writes:
>	I am new to C and I want to know how to get random numbers returned.

Unfortunately the specific details of pseudo-random number generators
in the system C libraries vary from system to system.  Usually there
is one called rand(), sometimes random().  UNIX System V has a family
*rand48().

ANSI C requires rand() to be provided, but probably your best bet for
the time being is to provide your own generator.  For example:

	static unsigned long next = 1;

	int my_rand()	/* returns range [0,32767] uniformly distributed */
	{
		next = next * 1103515245 + 12345;
		return (int)((unsigned)(next / 65536) * 32768);
	}

	void my_srand(seed)	/* sets the "seed" */
		int seed;
	{
		next = seed;
	}

This will be good enough for games, etc. but if you're doing intricate
statistical stuff (cryptosystems or Monte Carlo integration) you will
probably want to study up on RNGs; Knuth Vol. 2 is a good place to start.

mark@jhereg.Jhereg.MN.ORG (Mark H. Colburn) (02/03/89)

In article <19415@dhw68k.cts.com> tsource@dhw68k.cts.com (Aryeh Friedman) writes:
>	I am new to C and I want to know how to get random numbers returned.


There are several different variations on how to get random numbers in C.

On most System V based systems and when using ANSI C you would use the 
function srand() to provide a random number seed (if you want one) and 
the rand() function to get a randon number back.

	unsigned int	seed;
	int		num;

	seed = ???;
	srand(seed);
	num = rand();


On most BSD derived systems you would use srandom() to provide the seen and 
the random() function to get the random number back.


	int		seed;
	long		num;

	seed = ???;
	srandom(seed);
	num  = random();

-- 
Mark H. Colburn                  "Look into a child's eye;
Minnetech Consulting, Inc.        there's no hate and there's no lie;
mark@jhereg.mn.org                there's no black and there's no white."

bagpiper@oxy.edu (Michael Paul Hunter) (02/06/89)

In article <9570@smoke.BRL.MIL> gwyn@smoke.BRL.MIL (Doug Gwyn ) writes:
>In article <19415@dhw68k.cts.com> tsource@dhw68k.cts.com (Aryeh Friedman) writes:
>>	 I am new to C and I want to know how to get random numbers returned.
>
>Unfortunately the specific details of pseudo-random number generators
>in the system C libraries vary from system to system.	Usually there
>is one called rand(), sometimes random().  UNIX System V has a family
>*rand48().
>
>ANSI C requires rand() to be provided, but probably your best bet for
>the time being is to provide your own generator.  For example:
>

How about a quick hack at a random number generator that is
kindof-fairly uniorm in [0, 1].  My quick answer is to scale
rand...but that doesn't seem to be the best quick hack answer
to me.

				    Mike

gwyn@smoke.BRL.MIL (Doug Gwyn ) (02/07/89)

In article <16034@tiger.oxy.edu> bagpiper@oxy.edu (Michael Paul Hunter) writes:
>How about a quick hack at a random number generator that is
>kindof-fairly uniorm in [0, 1].  My quick answer is to scale
>rand...but that doesn't seem to be the best quick hack answer
>to me.

I think it is.  If you really need extremely good random deviates
then you have a lot of research and hard work to do.

Before somebody mentions the recent CACM article, let me denounce
it as not contributing significantly to this subject.

By the way, I find that [0,1) (i.e. including 0 but excluding 1)
is a more useful range.  The obvious implementation using the
previously-posted my_rand() is:

	extern int my_rand();  /* uniform integer in [0,32767] */
	double my_unif() { return my_rand() / 32768.0; }  /* [0.0,1.0) */

hascall@atanasoff.cs.iastate.edu (John Hascall) (02/07/89)

In article <16034@tiger.oxy.edu> bagpiper@oxy.edu (Michael Paul Hunter) writes:
>In article <9570@smoke.BRL.MIL> gwyn@smoke.BRL.MIL (Doug Gwyn ) writes:
>>In article <19415@dhw68k.cts.com> tsource@dhw68k.cts.com (Aryeh Friedman) writes:
>>>	 I am new to C and I want to know how to get random numbers returned.

>>ANSI C requires rand() to be provided, but probably your best bet for
>>the time being is to provide your own generator.  For example:

>How about a quick hack at a random number generator that is
>kindof-fairly uniorm in [0, 1].  My quick answer is to scale
>rand...but that doesn't seem to be the best quick hack answer
>to me.

    rand() s*cks (at least in VMS C, I don't know about others),
    I always MTH$RANDOM() rather than rand() on VMS systems.

    "The Art of Computer Programming", Vol II, Chap 3 should be
    of use.

	
	John Hascall

mcdonald@uxe.cso.uiuc.edu (02/08/89)

>I think it is.  If you really need extremely good random deviates
>then you have a lot of research and hard work to do.

I finally got tired of non-random random numbers, so
I hooked an ADC converter and a hot resistor to my computer and xor'ed the 
results from it with rand(). This gives me about 10000 really random numbers
a second. It is not trivial to get REALLLY random numbers out of such
a setup, but it can be done.
 

paulc@hpgrla.HP.COM (@Paul Charlton) (02/09/89)

geez...my favorite random number generator on a similar hardware vein is
 use the noise off of a cheap transistor, fed into a counter register...

 PaulC

 {paulc@hpgrai.hp.com} | {hplabs!hpgrai!paulc}

jima@hplsla.HP.COM (Jim Adcock) (02/10/89)

> I finally got tired of non-random random numbers, so
> I hooked an ADC converter and a hot resistor to my computer and xor'ed the 
> results from it with rand(). This gives me about 10000 really random numbers
> a second. It is not trivial to get REALLLY random numbers out of such
> a setup, but it can be done.

My concern would be with using the [multi-bit?] ADC.  We use a similar 
technique to generate noise sources for our FFT analysers, only using 
well known tapped shift registers, bitwise results xor'ed with a 
one-bit result from a one bit-ADC and a noise diode.  We then 
collect say 16-bits from the shift register to make a 16-bit word.
While neither the shift register nor the diode make all that great 
"random noise", the result of the xor is the convolution of their two 
spectrums, so the result is generally pretty good.  You still need to 
keep the shift register and the noise diode isolated though.

jima@hplsla.HP.COM (Jim Adcock) (02/10/89)

/* 1) caveat emptor                       */
/* 2) assumes 16 bit shorts, 32 bit longs */
/* 3) takes about 15 uSec on a mid performance 68020 system, 
      takes about  4 uSec on a 840 system */
/* 4) pseudo random noise generator, 31 bit long shift register,
      Mersenne prime, 16 shifts calculated at a time, returning
      a 16-bit unsigned short.  Sequence length 2,147,483,647 */

static prngshift = 3141592654;
unsigned short prng();

void prnginit(initseed)
unsigned long initseed;
{
    register i;
    initseed *= 456295141;
    prngshift = initseed^3141592654;
    if (!prngshift) prngshift = 3141592654;
    for (i=0; i<6; ++i) prng();
}

unsigned short prng()
{
    register unsigned long  d0, d1;
    register unsigned short lo;

    d1 = prngshift;
    d0 = d1>>16;
    d1 <<= 16;
    d0 |= d1;
    d0 = d0<<1 | d0>>31;
    lo = d0;
    d0 = d0<<4 | d0>>28;
    lo ^= d0;
    d0 = d0<<8 | d0>>24;
    lo ^= d0;
    d0 = d0<<2 | d0>>30;
    lo ^= d0;
    d1 |= lo;
    prngshift = d1;
    return lo;
}

levy@ttrdc.UUCP (Daniel R. Levy) (02/12/89)

In article <225800121@uxe.cso.uiuc.edu>, mcdonald@uxe.cso.uiuc.edu writes:
< I hooked an ADC converter and a hot resistor to my computer and xor'ed the 
                                                              --------------
< results from it with rand(). This gives me about 10000 really random numbers
  ---------------------------
< a second. It is not trivial to get REALLLY random numbers out of such
< a setup, but it can be done.

Why?  Why not use the pure output of your device?  (presuming it has the needed
dynamic range)
-- 
Daniel R. Levy             UNIX(R) mail:  att!ttbcad!levy
AT&T Bell Laboratories
5555 West Touhy Avenue     Any opinions expressed in the message above are
Skokie, Illinois  60077    mine, and not necessarily AT&T's.

bradb@ai.toronto.edu (Brad Brown) (02/12/89)

>In article <225800121@uxe.cso.uiuc.edu>, mcdonald@uxe.cso.uiuc.edu writes:
>I hooked an ADC converter and a hot resistor to my computer and xor'ed the 
>results from it with rand(). This gives me about 10000 really random numbers
>a second. It is not trivial to get REALLLY random numbers out of such
>a setup, but it can be done.


I'm curious -- how do you ensure the spectral purity of the signal that
you sample with the ADC?  Also how do you calibrate the measurement so
that the samples are uniformly distributed over the *entire* dynamic
range of the ADC?

					(-:  Brad Brown  :-)
					bradb@ai.toronto.edu

bengsig@orcenl.uucp (Bjorn Engsig) (02/13/89)

In article <4080003@hpgrla.HP.COM> paulc@hpgrla.HP.COM (@Paul Charlton) writes:
>geez...my favorite random number generator on a similar hardware vein is
> use the noise off of a cheap transistor, fed into a counter register...
I thought this was comp.lang.c and not comp.hardware.noise.
-- 
Bjorn Engsig, ORACLE Europe         \ /    "Hofstadter's Law:  It always takes
EUnet path: mcvax!orcenl!bengsig     X      longer than you expect, even if you
USA domain: bengsig@oracle.com      / \     take into account Hofstadter's Law"

jwp@larry.UUCP (Jeffrey W Percival) (02/13/89)

>I think it is.  If you really need extremely good random deviates
>then you have a lot of research and hard work to do.

Why is this true?  No one tells me that if I want a *really* good C
compiler, I have a lot of work to do, or if I want a *really* good
operating system, I have a lot of work to do.

The way I see it, a bizillion people work very hard, and as a result,
I have on my desk a VAX with a *great* operating system, plenty of
disk, a hundred megabytes of secondary storage, a nice programming
language, a fast, efficient compiler, but when it comes to decent
random numbers, the user sees a big "go jump in a lake".

Now, I understand that the poster of the lead statement above was NOT
saying that, he was referring to the fact that this is a tough
problem.  Understood.  But, as far as *I* am concerned, so is designing
a chip, or a language.  They are *all* tough problems, but they are
solved by experts for consumers.  Random numbers in computers are not a
new need, or a minor need.  Why, you computer industry out there, have
you left one big turd in the middle of a *great* superhighway?
-- 
Jeff Percival (jwp@larry.sal.wisc.edu)

henry@utzoo.uucp (Henry Spencer) (02/14/89)

In article <514@larry.UUCP> jwp@larry.UUCP (Jeffrey W Percival) writes:
>Why is this true?  No one tells me that if I want a *really* good C
>compiler, I have a lot of work to do, or if I want a *really* good
>operating system, I have a lot of work to do.

That's because it's normally considered to be taken for granted.  No,
I am not kidding -- *really* good C compilers are very rare, and I'm
not sure that there has ever been a *reall* good operating system.
-- 
The Earth is our mother;       |     Henry Spencer at U of Toronto Zoology
our nine months are up.        | uunet!attcan!utzoo!henry henry@zoo.toronto.edu

desnoyer@Apple.COM (Peter Desnoyers) (02/14/89)

In article <514@larry.UUCP> jwp@larry.UUCP (Jeffrey W Percival) writes: 
>>I think it is.  If you really need extremely good random deviates 
>>then you have a lot of research and hard work to do.  
>
>Why is this true?  No one tells me that if I want a *really* good C
>compiler, I have a lot of work to do, or if I want a *really* good
>operating system, I have a lot of work to do.  
> 

If you program in SIMSCRIPT or SIMULA or any other simulation language
(except GPSS) you will get a fine random number generator at your
disposal. C was evidently designed by people who didn't need random
numbers - the standardized rand() doesn't allow a seed to be
specified, making it useless when you need independent streams of
random numbers.

BTW, you don't need to do a lot of work - just look up a few
references. Any reasonably theoretical book on simulation should go
into generation of random deviates, spectral measures of randomness,
etc. You can usually skip most of that and copy an algorithm from
Knuth, anyway.

				Peter Desnoyers

mcdonald@uxe.cso.uiuc.edu (02/14/89)

>
>If you program in SIMSCRIPT or SIMULA or any other simulation language
>(except GPSS) you will get a fine random number generator at your
>disposal. C was evidently designed by people who didn't need random
>numbers - the standardized rand() doesn't allow a seed to be
>specified, making it useless when you need independent streams of
>random numbers.

>BTW, you don't need to do a lot of work - just look up a few
>references. Any reasonably theoretical book on simulation should go
>into generation of random deviates, spectral measures of randomness,
>etc. You can usually skip most of that and copy an algorithm from
>Knuth, anyway.


Depends on how important it is that your numbers are really random.
If it matters, I suggest that YOU figure out what property of randomness
matters most to you, and test it on a possible generator candidate.

Let me tell a little story: A friend, who worked for the leading 
professor in the field, was doing classical dynamical trajectories
on molecules. The initial conditions come in ordered triples,
i.e. x, y, and z or px, py, pz. It seems that the standard IBM
360 Fortran random generator generated triples, all of which 
lay in eight planes in three-space. And - one of these planes
passed through a near-singularity in the results. Result:
final results which weren't right - by a lot. Luckily this guy 
was smart enough to figure out from the answer what was happening.

The properties listed in books may NOT be the ones that matter to YOU.

Doug McDonald

henry@utzoo.uucp (Henry Spencer) (02/14/89)

In article <25745@apple.Apple.COM> desnoyer@Apple.COM (Peter Desnoyers) writes:
>... C was evidently designed by people who didn't need random
>numbers - the standardized rand() doesn't allow a seed to be
>specified, making it useless when you need independent streams of
>random numbers.

Please read manual before flaming about it.  The V7 rand() allowed a
seed to be specified, as (I think) did earlier ones.  And so does
ANSI C (Oct draft) -- in fact the ANSI C spec for rand() is essentially
the V7 one.  If the C you use has broken this, complain to your supplier.
-- 
The Earth is our mother;       |     Henry Spencer at U of Toronto Zoology
our nine months are up.        | uunet!attcan!utzoo!henry henry@zoo.toronto.edu

bagpiper@oxy.edu (Michael Paul Hunter) (02/15/89)

In article <225800121@uxe.cso.uiuc.edu> mcdonald@uxe.cso.uiuc.edu writes:
>
>
>>I think it is.  If you really need extremely good random deviates
>>then you have a lot of research and hard work to do.
>
>I finally got tired of non-random random numbers, so
>I hooked an ADC converter and a hot resistor to my computer and xor'ed the
>results from it with rand(). This gives me about 10000 really random numbers
>a second. It is not trivial to get REALLLY random numbers out of such
>a setup, but it can be done.
>
Unfortunately it is hard to reproduce sequences of numbers using this
method, which makes modeling a bit hairy!!

				     Mike

jima@hplsla.HP.COM (Jim Adcock) (02/15/89)

> geez...my favorite random number generator on a similar hardware vein is
>  use the noise off of a cheap transistor, fed into a counter register...

I would not expect this to be a good random number generator --
unless the time between successive readings of the counter is itself a
pretty random amount of time, or the counter goes through a very large
number of complete cycles between subsequent readings.  Otherwise you
can expect a fair amount of correlation between subsequent numbers.

Most trivial "hardware" solutions fail to give very random numbers
for reasons that are very similar to reasons trivial "software"
solutions fail to give very random numbers.

XOR'ing a "hardware [noise-diode-like]" solution with a "software"
solution can give a better overall solution if both are very good
"random" number generators to begin with,  whose individual bits
are all "zero mean" [equal probability of ones and zeros.]

Its extremely hard to make good random number generators using
a purely hardware approach, since its hard to make analog noise
that doesn't have any 60Hz, 120Hz, 180Hz, chopper power supply
frequencies, feedthru from the electronics of the computer
you're attached to, etc.

...And if you're using a custom designed "hardware" [and/or 
software] solution you still need to "prove" that your
"random numbers" pass all the common simple tests of
randomness.  Which they probably won't.

...And if you use a combined hardware/software solution, then
you lose the repeatability that setting a seed in a purely
"software" solution gives you.

For example, we frequently use random numbers to test software,
using the random numbers to choose from the various commands that
our software implements, with randomly selected parameters,
in random order.  Its very nice to use this technique to 
find software bugs, fix the bugs, then re-run the random command
generator software with the same seed as a regression test.
Can't do this with a combined hardware/software scheme.

While, for many trivial applications, like playing games,
one may not care too much how good your random numbers
are, but in many cases one needs to be able to assume
the numbers really are "random" in order to be able to
make reasonable statistical assumptions about whatever
it is one's testing.

In summary, there's lots of simple, trivial, fast, but lousy
ways to make random numbers in either hardware and/or software.
Test what you would use.  Caveat Emptor.

gwyn@smoke.BRL.MIL (Doug Gwyn ) (02/16/89)

In article <225800132@uxe.cso.uiuc.edu> mcdonald@uxe.cso.uiuc.edu writes:
>Let me tell a little story: ...

Here's mine:  Long ago, in an agency far far away, I helped produce
reams of "random" teleprinter output which was intended to be used
as "background" into which "bust" samples were to be inserted.  The
"busts" represented output that would be obtained if certain items
or procedures in a cryptosystem broke down.  (All this was for
training cryptanalysis students in the visual recognition of
possible "busts" which would then be subjected to further analysis.)
The problem was, no matter how hard I worked to produce "random"
output using standard pseudo-random sequence generators, my output
exhibited regularities that the experienced instructors immediately
spotted as symptomatic of certain classes of "busts".  This rather
interfered with its use as random background...

henry@utzoo.uucp (Henry Spencer) (02/16/89)

In article <1989Feb14.154157.15148@utzoo.uucp> I wrote:
>>... the standardized rand() doesn't allow a seed to be
>>specified...
>
>Please read manual before flaming about it.  The V7 rand() allowed a
>seed to be specified, as (I think) did earlier ones....

However, as has been pointed out to me in private mail, the key issue when
you want multiple streams of random numbers is not being able to specify
a seed, but being able to save the state of rand() and restore it later.
*That*, the standard rand() can't do.
-- 
The Earth is our mother;       |     Henry Spencer at U of Toronto Zoology
our nine months are up.        | uunet!attcan!utzoo!henry henry@zoo.toronto.edu

albaugh@dms.UUCP (Mike Albaugh) (02/16/89)

	I have exactly reversed the orrder of the following paragraphs,
to more naturally convey my comments/objections.
From article <5260010@hplsla.HP.COM>, by jima@hplsla.HP.COM (Jim Adcock):
> In summary, there's lots of simple, trivial, fast, but lousy
> ways to make random numbers in either hardware and/or software.
> Test what you would use.  Caveat Emptor.

	Agreed wholeheartedly, and I do _not_ wish to minimize this point!

> While, for many trivial applications, like playing games,
                  ^^^^^^^                    ^^^^^^^^^^^^^
> one may not care too much how good your random numbers
> are, but in many cases one needs to be able to assume
> the numbers really are "random" in order to be able to
> make reasonable statistical assumptions about whatever
> it is one's testing.

	Watch whose baby you call ugly ( :-) ). We (I) spend a great deal
of effort here on random number generation. We have some additional
constraints, because "really" random numbers tend to be viewed quite
skeptically by the general public. In general we try very hard to model
some actual physical (or psychological) system and use randomness only
where appropriate, deep within the model,rather than forming some gross
effect totally out of "random" numbers. This tends to ameliorate the
problem, but I wish to emphasize that if you need random numbers at all
you need good ones. How many of you would settle for a sin() that was,
well, sort of ok usually ?. (That many? :-) how about integer multiply?)

	Not to side _too_ completely with the original poster (lamenting
the lack of a "good" random number generator as part of the library). If
you know enough about your problem to wrap the right post-processing
around a good rand(), you probably know enough to write it from scratch
(with a finger in Knuth). If you don't, then what difference can the quality
of rand() make?

> For example, we frequently use random numbers to test software,
> using the random numbers to choose from the various commands that
> our software implements, with randomly selected parameters,
> in random order.  Its very nice to use this technique to 
> find software bugs, fix the bugs, then re-run the random command
> generator software with the same seed as a regression test.
> Can't do this with a combined hardware/software scheme.

	I would think that a better approach would be to generate the
whole stream ahead of time (with timings info as to _when_ commands
are entered), or to log it (again with timestamps) as it is generated.
Then a hardware, software, or "thousand monkeys" (software test group
of "naive users") method can be used at will, and re-play for regression
testing would be a snap.

	Yes, everybody, I agree this is getting rather far from comp.lang.c.
I promise to shut up now.
				Mike

diamond@diamond.csl.sony.junet (Norman Diamond) (02/16/89)

> > geez...my favorite random number generator on a similar hardware vein is
> >  use the noise off of a cheap transistor, fed into a counter register...

> I would not expect this to be a good random number generator --
> can expect a fair amount of correlation between subsequent numbers.

True.  And xor'ing with software computations is better.

> ...And if you use a combined hardware/software solution, then
> you lose the repeatability that setting a seed in a purely
> "software" solution gives you.
> For example, we frequently use random numbers to test software,
> using the random numbers to choose from the various commands that
> our software implements, with randomly selected parameters,
> in random order.  Its very nice to use this technique to 
> find software bugs, fix the bugs, then re-run the random command
> generator software with the same seed as a regression test.
> Can't do this with a combined hardware/software scheme.

You can, by making a database of your random numbers.

It all comes down to this:  our real need is for a stream of numbers that
appears random to the program or naive user, but is reproducible on demand.
This is like asking whether an operating system should provide for tasks to
communicate or to compete.  The answer is both.
Norman Diamond, Sony Computer Science Lab (diamond%csl.sony.jp@relay.cs.net)
  The above opinions are my own.   |  Why are programmers criticized for
  If they're also your opinions,   |  re-inventing the wheel, when car
  you're infringing my copyright.  |  manufacturers are praised for it?

tsource@dhw68k.cts.com (Aryeh Friedman) (02/16/89)

In article <1989Feb14.154157.15148@utzoo.uucp> henry@utzoo.uucp (Henry Spencer) writes:
>Please read manual before flaming about it.  The V7 rand() allowed a
>seed to be specified, as (I think) did earlier ones. 

I am using Berkeley UNIX and I can seed using srand.  BTW All I ever wanted to  was use it for a game.
-- 
Aryeh Friedman (aka The source)
tsource@dhw68k.cts.COM or tsource@dhw68k.UUCP

bill@twwells.uucp (T. William Wells) (02/16/89)

In article <619@dms.UUCP> albaugh@dms.UUCP (Mike Albaugh) writes:
:       I would think that a better approach would be to generate the
: whole stream ahead of time (with timings info as to _when_ commands
: are entered), or to log it (again with timestamps) as it is generated.
: Then a hardware, software, or "thousand monkeys" (software test group
: of "naive users") method can be used at will, and re-play for regression
: testing would be a snap.

This is not practical if the generated stream is very large. For
example, when I do this kind of testing on a memory allocator, the
number of requests might well be in the millions or billions.

Even if the disk space existed to store such, the time needed to read
it in would dwarf the time needed to regenerate the stream with the
random number generator.

---
Bill
{ uunet!proxftl | novavax } !twwells!bill

chris@mimsy.UUCP (Chris Torek) (02/17/89)

In article <1989Feb15.213335.18135@utzoo.uucp> [love those message-IDs]
henry@utzoo.uucp (Henry Spencer) writes:
>However, as has been pointed out to me in private mail, the key issue when
>you want multiple streams of random numbers is not being able to specify
>a seed, but being able to save the state of rand() and restore it later.
>*That*, the standard rand() can't do.

Well, actually you can (as I pointed out in private mail, but I think
not coherently).  It is not suitable except as an exercise, but it goes
like this:

	struct rand_stream {
		int	rs_seed;
		unsigned long rs_calls;
	};

	struct rand_stream *rs_start(int seed) {
		struct rand_stream *rs = malloc(sizeof(*rs));

		if (rs == NULL)
			return (NULL);
		rs->rs_seed = seed;
		rs->rs_calls = 0;
	}

	int rs_rand(struct rand_stream *rs) {
		unsigned long l;

		srand(rs->rs_seed);
		for (l = 0; l < rs->rs_calls; l++)
			(void) rand();
		rs->rs_calls++;
		return (rand());
	}

Incidentally, one of the big features of `object oriented' languages
is that they encourage encapsulation of state into a data object,
eliminating on a local level global (static) variables, obviating
the need for the above sort of chicanery.
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris@mimsy.umd.edu	Path:	uunet!mimsy!chris

childers@avsd.UUCP (Richard Childers) (02/17/89)

jwp@larry.UUCP (Jeffrey W Percival) writes:

>... but when it comes to decent random numbers, the user sees a big
>"go jump in a lake".

If someone asks you for the perfect programming language, give them a lollipop.

>... as far as *I* am concerned ... Random numbers in computers are not a new
>or minor need. Why, you computer industry out there, have you left one big
>turd in the middle of a *great* superhighway?

In some respects, you've answered this yourself. Most people don't see it,
they're intent on where they are going, and they're going too fast. They
don't even notice the bump. Databases don't use ramdon numbers much ...

More generally, random numbers are useful only for games, simulations, and
cryptographic applications. Of those three applications, only one of them
is profitable enough to have generated its own hardware, DES-on-a-chip, as
it were, thus fulfilling your demand for such a product.

Of the remaining two, games and simulations, the people involved usually run
up against the problem and understand its nature when they try to solve it,
as they are dealing with pools of probability that need to be massaged into
a precise configuration, and are usually reasonably sophisticated at math.
If you were to do this, you would find that it is still an unsolved challenge
to derive a good random number, and there is room for original work. Which is
kind of nice to know, I think ...


>Jeff Percival (jwp@larry.sal.wisc.edu)

-- richard

-- 
 *                Any excuse will serve a tyrant.      -- Aesop               *
 *                                                                            *
 *           ..{amdahl,decwrl,octopus,pyramid,ucbvax}!avsd!childers           *
 *             AMPEX Corporation - Video Systems Division, R & D              *

boyne@hplvli.HP.COM (Art Boyne) (02/17/89)

albaugh@dms.UUCP (Mike Albaugh) writes:

>From article <5260010@hplsla.HP.COM>, by jima@hplsla.HP.COM (Jim Adcock):
>> For example, we frequently use random numbers to test software,
>> using the random numbers to choose from the various commands that
>> our software implements, with randomly selected parameters,
>> in random order.  Its very nice to use this technique to 
>> find software bugs, fix the bugs, then re-run the random command
>> generator software with the same seed as a regression test.
>> Can't do this with a combined hardware/software scheme.
>
>	I would think that a better approach would be to generate the
>whole stream ahead of time (with timings info as to _when_ commands
>are entered), or to log it (again with timestamps) as it is generated.
>Then a hardware, software, or "thousand monkeys" (software test group
>of "naive users") method can be used at will, and re-play for regression
>testing would be a snap.

Sorry, Mike, but I agree with the original poster (Jim Adccock), and NOT
because I happen to work for the same company (different division, though).
Having a set of pre-defined commands with timing is necessary, and allows
you to test most corner cases, but random command/parameter combinations DO
catch a lot of "Gee, I never would have tried THAT" type bugs.  And sending
those commands at random time intervals, especially things like Device Clear
over IEEE-488 (GP-IB), is a good way to catch races and unprotected critical
code sections.  Using a fixed starting random number seed make the test
repeatable.

Art Boyne, boyne@hplvla.hp.com