Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

How can I generate random numbers?

179 views
Skip to first unread message

P.Bennett

unread,
Oct 9, 1996, 3:00:00 AM10/9/96
to

In article <01bbb643$623c3e80$3d2f...@normi.actcom.co.il>, "Nir Izsak" <no...@actcom.co.il> writes...
>I Have Visual C++ 4.0.
>How can I generate random numbers?
>I know that the function is rand, but I don't know how to use it.
>I receive PSEIDO-RANDOM numbers.

rand() does generate pseudo-random numbers. It is common to "seed" rand() with
the aid of srand() to get a different sequence of "random" numbers each time
the program is run.

One common way to get a random-ish seed is: (stolen from Borland C on-line
help)

int main(void)
{
int i;
time_t t;

srand((unsigned) time(&t));
printf("Ten random numbers from 0 to 99\n\n");
for(i=0; i<10; i++)
printf("%d\n", rand() % 100);
return 0;
}


Peter Bennett VE7CEI | Vessels shall be deemed to be in sight
Internet: ben...@triumf.ca | of one another only when one can be
Packet: ve7cei@ve7kit.#vanc.bc.ca | observed visually from the other
TRIUMF, Vancouver, B.C., Canada | ColRegs 3(k)
GPS and NMEA info and programs: ftp://sundae.triumf.ca/pub/peter/index.html
or: ftp://ftp-i2.informatik.rwth-aachen.de/pub/arnd/GPS/peter/index.html
or: http://vancouver-webpages.com/peter/index.html


Nir Izsak

unread,
Oct 10, 1996, 3:00:00 AM10/10/96
to

I Have Visual C++ 4.0.
How can I generate random numbers?
I know that the function is rand, but I don't know how to use it.
I receive PSEIDO-RANDOM numbers.
-----------------------------------------------
Sent by Nir Izsak
-----------------------------------------------
E-Mail: no...@actcom.co.il
-----------------------------------------------
Send answers to my E-Mail

Cecil A. Galbraith

unread,
Oct 10, 1996, 3:00:00 AM10/10/96
to Nir Izsak

Get married and give your wife a checkbook...

--
Cecil Galbraith
cgal...@concentric.net
CustomSoft

Download free programmers utilities at
http://www.concentric.net/~cgalbrai/

Larry Baker

unread,
Oct 10, 1996, 3:00:00 AM10/10/96
to P.Bennett

P.Bennett wrote:
> a nice example on using rand() for random-number generation.

Beware. rand() "randomness" varies from vendor to vendor. If
all you're looking for is something lightweight like randomness in
a game, rand() will do fine; if you're doing statistical simulations
or monte-carlo simluations or something really heavyweight, I'd
consider some of the published algorithms, e.g. from Numerical
Recepies or Sedgewick's Algorithms books.

Cheers,

Larry Baker

John Grant

unread,
Oct 11, 1996, 3:00:00 AM10/11/96
to

In article <01bbb643$623c3e80$3d2f...@normi.actcom.co.il> "Nir Izsak" <no...@actcom.co.il> writes:
>I Have Visual C++ 4.0.
>How can I generate random numbers?
>I know that the function is rand, but I don't know how to use it.
>I receive PSEIDO-RANDOM numbers.
Exactly. That's what most built-in rand functions do. They're not
really for serious random number work. I can recommend the Numerical
Recipes book for a good discussion of random numbers, complete with
several functions already written for you (you can get FORTRAN, C etc
versions of the book). Lots of source code,. and the book is quite
practical and relatively easy to read.
--
John A. Grant * I speak only for myself * jag...@nrcan.gc.ca
Airborne Geophysics, Geological Survey of Canada, Ottawa
If you followup, please do NOT e-mail me a copy: I will read it here.

Dan Evens

unread,
Oct 11, 1996, 3:00:00 AM10/11/96
to

Cecil A. Galbraith wrote:

> Nir Izsak wrote:
> > How can I generate random numbers?
> Get married and give your wife a checkbook...

But that sequence is monotonic increasing.

--
The preceding are my opinions alone and have nothing
whatever to do with my employer. I don't even know what my
employer thinks. I'm not even real sure who the CEO is.
Dan Evens

Bruce Wedding

unread,
Oct 12, 1996, 3:00:00 AM10/12/96
to

In comp.lang.c
jag...@emr1.NRCan.gc.ca (John Grant) wrote:

> Exactly. That's what most built-in rand functions do.
> They're not really for serious random number work.
> I can recommend the Numerical Recipes book for a
> good discussion of random numbers, complete

If you want TRUE random numbers, you can now get them
off the web. Quoting from the page:

"HotBits is an Internet resource that brings genuine random
numbers, generated by a process fundamentally governed by
the inherent uncertainty in the quantum mechanical laws of
nature, directly to your computer in a variety of forms.
HotBits are generated by timing successive pairs of
radioactive decays detected by a Geiger-Müller tube
interfaced to a computer. You order up your serving of
HotBits by filling out a request form specifying how many
random bytes you want and in which format you'd like them
delivered. Your request is relayed to the HotBits server,
which flashes the random bytes back to you over the Web. "

You can find them at:
http://www.fourmilab.ch/hotbits/

Bruce

Ed Breen

unread,
Oct 12, 1996, 3:00:00 AM10/12/96
to

"LionKing!" <mafa...@frcu.eun.eg> wrote:

>Nir Izsak wrote:
>>
>> I Have Visual C++ 4.0.
>> How can I generate random numbers?
>> I know that the function is rand, but I don't know how to use it.
>> I receive PSEIDO-RANDOM numbers.
>> -----------------------------------------------
>> Sent by Nir Izsak
>> -----------------------------------------------
>> E-Mail: no...@actcom.co.il
>> -----------------------------------------------
>> Send answers to my E-Mail
>
>As Far as I recall from my memory (which is like Win32s),
>rand takes 1 param this param is the range bound meaning;
>if you say :
> x = rand (128);
>
> this will evaluate x to a random number from 0 to 128 ...
>
> have fun ...
>

The prototype declaration for ANSI C's rand is:

#include <stdlib.h>
int rand(void);

As you see your memory has let you down.

Now, if you want a constrained value, then try

rand()%129;

This will range from 0 to 128.


--
------------------------------------------------------------------
Ed Breen
CSIRO, DMS Phone:+61 2 325 3208
Locked Bag 17, Nth Ryde Fax:+61 2 325 3200
NSW, Australia 2113 E-mail:e...@syd.dms.csiro.au
Building E6B URL:http://www.dms.csiro.au/~edb
Macquarie University Campus
------------------------------------------------------------------


Jason Haney

unread,
Oct 12, 1996, 3:00:00 AM10/12/96
to

Cecil A. Galbraith <cgal...@cris.com> wrote:
: Nir Izsak wrote:
: >
: > I Have Visual C++ 4.0.
: > How can I generate random numbers?

: Get married and give your wife a checkbook...

HA!! That was good!!

--jason

-----
South Jersey Internet Services
Internet strategies for business on the World Wide Web
http://www.sjis.com/ in...@sjis.com (609) 224-0701

Steve Brecher

unread,
Oct 12, 1996, 3:00:00 AM10/12/96
to

Ed Breen <e...@syd.dms.csiro.au> wrote:

> The prototype declaration for ANSI C's rand is:
>
> #include <stdlib.h>
> int rand(void);
>

> [...]


>
> Now, if you want a constrained value, then try
>
> rand()%129;
>
> This will range from 0 to 128.

The above is correct, but the result will not necessarily be uniformly
distributed over [0,128], even if the result of rand() is uniformly
distributed over [0,RAND_MAX].

Consider the case in which RAND_MAX is 65535. The largest multiple of 129
in 65535 is 65532 (508 times 129). So if you enumerate the possible
return values of rand() and map each to the result of rand()%129, it would
look like:

0 -> 0
1 -> 1
2 -> 2
...
128 -> 128
129 -> 0
...
65532 -> 0
65533 -> 1
65534 -> 2
65535 -> 3

and hence if you tablulate the distribution of results of rand()%129, the
values 1, 2, and 3 will occur 509 times each, while the values 0 and 4
through 128 will occur 508 times each.

Following is a C++ member function that illustrates a way to provide a
uniformly distributed result constrained to range over [0,ceiling), i.e.,
[0,ceiling-1]. In this code, Random() is analogous to rand(), and
Max_Random() is analogous to RAND_MAX. Executive summary: reject values
of the underlying generator which are larger than or equal to the largest
multiple of the ceiling. This technique is fairly efficient for usage in
which the ceiling value is reasonably small compared to Max_Random().
Note that the code does not check for illegal argument values -- 0 and
values > Max_Random(); the class from which this is taken provides another
version (not shown) which does check.

#if RNG_cache_size
static unsigned int g_max_multiple_cache[RNG_cache_size];
#endif

unsigned int RNG_C::Random_Under(unsigned int const ceiling)
// In order for the result to have uniform distribution, we reject values
// of Random() which are greater than or equal to
// (Max_Random() / ceiling) * ceiling.
// E.g., suppose Max_Random() were 105 and we wanted a variate uniformly
// distributed over [0,9], i.e., ceiling of 10. If the rejection of
// Random() values in [100,105] were not performed, the values in [0,5]
// would be over-represented. Cacheing the rejection criterion reduces
// execution time for small ceilings at the cost of RAM for the cache.
// [at least on my platform -- S.B.]
{
unsigned int raw_random, max_multiple_of_ceiling;

#if RNG_cache_size
if (ceiling < RNG_cache_size) {
if (!(max_multiple_of_ceiling = g_max_multiple_cache[ceiling]))
g_max_multiple_cache[ceiling] = max_multiple_of_ceiling =
(Max_Random() / ceiling) * ceiling; }
else
#endif
max_multiple_of_ceiling = (Max_Random() / ceiling) * ceiling;

do
raw_random = Random();
while (raw_random >= max_multiple_of_ceiling);

return raw_random % ceiling;
}

--
st...@brecher.reno.nv.us (Steve Brecher)

Jerry Coffin

unread,
Oct 12, 1996, 3:00:00 AM10/12/96
to

In article <Dz5M2...@news.nsw.CSIRO.AU>, e...@syd.dms.csiro.au
says...

[ ... ]

> Now, if you want a constrained value, then try
>
> rand()%129;
>
> This will range from 0 to 128.

It will also be skewed so some values are more likely to occur than
others. with some implementations of rand() it will also be less
random than it could otherwise be, because it retains less significant
bits from the generator, which are generally less random than more
significant bits. Fortunately avoiding these problems adds only a
miniscule bit of code:

#include <stdlib.h>

int rand_lim(int limit) {
/* return a random number between 0 and limit inclusive.
**/

int divisor = RAND_MAX / (limit + 1);
int retval;

while (limit+1 >=(retval= rand() / divisor))
;
return retval;
}

This produces numbers within the specified range with as good of
quality as the underlying implementation of rand().

--
Later,
Jerry.

LionKing!

unread,
Oct 13, 1996, 3:00:00 AM10/13/96
to

Nir Izsak wrote:
>
> I Have Visual C++ 4.0.
> How can I generate random numbers?

Daniel Bouganim

unread,
Oct 14, 1996, 3:00:00 AM10/14/96
to

And... You can not normalize the sequence.

Dan Evens <dan....@hydro.on.ca> wrote in article
<325E5B...@hydro.on.ca>...


> Cecil A. Galbraith wrote:
> > Nir Izsak wrote:

> > > How can I generate random numbers?

> > Get married and give your wife a checkbook...
>

Dhiraj Thakkar

unread,
Oct 14, 1996, 3:00:00 AM10/14/96
to

Ed Breen (e...@syd.dms.csiro.au) wrote:
> "LionKing!" <mafa...@frcu.eun.eg> wrote:

> The prototype declaration for ANSI C's rand is:

> #include <stdlib.h>
> int rand(void);

...deleted

> Now, if you want a constrained value, then try

> rand()%129;

> This will range from 0 to 128.

Numerical recipes author mention that the lower bits are not well randomized
by commonly used random number generators (linear congruential generators).
So a good way to generate a random number from n to m would be to take higer
order bits like:
n + (((double) rand() / RAND_MAX) * m);

--Dhiraj

Slawomir Marczynski

unread,
Oct 15, 1996, 3:00:00 AM10/15/96
to

John Grant (jag...@emr1.NRCan.gc.ca) wrote:
: >How can I generate random numbers?
: >I receive PSEIDO-RANDOM numbers.
: Exactly. That's what most built-in rand functions do. They're not

Just _all_ random numbers routines gives only pseudo-random numbers on
output. There are something in the concept of a "procedure", which gives
us a suspicion that results will be repeatable. You should use a special
hardware to obtain "true" random numbers - maybe a noise diode or similar
devices. The hardware may be quite expensive and there are two reasons to
don't use it. First, you probably don't need a really random numbers,
even in very serious Monte Carlo computations. Second, the true random
numbers generated by a black box should be verified - and there is a very
little chance to verify (without any pre-assumptions) that the black
box work fine.

YS
--
Slawomir Marczynski (Mr)
Institute of Physics, Technical University of Szczecin
Al. Piastow 48/49, 70-310 Szczecin, Poland
sla...@arcadia.inter.tuniv.szczecin.pl, tel:+(048-91)-494056

Kent Budge

unread,
Oct 15, 1996, 3:00:00 AM10/15/96
to

Slawomir Marczynski wrote:
...

> don't use it. First, you probably don't need a really random numbers,
> even in very serious Monte Carlo computations. Second, the true random
...

In fact, improved Monte Carlo integration deliberately uses sub-random
sequences (Sobolev sequences) that have very definite correlations.
The result is a method that converges faster (for appropriate
integrands) than conventional Monte Carlo using truly random numbers.

--
Kent G. Budge
kgb...@sandia.gov
(usual disclaimer)
Return address hacked to foil junk mail; edit before replying.

Doug Miller

unread,
Oct 15, 1996, 3:00:00 AM10/15/96
to

Dan Evens <dan....@hydro.on.ca> wrote:
>Cecil A. Galbraith wrote:
>> Nir Izsak wrote:
>> > How can I generate random numbers?
>> Get married and give your wife a checkbook...
>
>But that sequence is monotonic increasing.
>
Don't you mean monotonic DEcreasing?

Doug Miller
dlmi...@inetdirect.net ('from' field rigged to foil e-mail spammers)
views expressed are mine and not those of
Hospital Health Plan Corp. "all health care is local"


Steven Truax

unread,
Oct 16, 1996, 3:00:00 AM10/16/96
to

I have a question about converting a 'long' variable into a 'char' type
variable. Let me give you the
situation...

Files were written in the past using this 'long' variable. Now, instead
of placing an integer into the
variable such as '12', I would like to place the value '12a' into this
pre-existing variable. My
problem is therefore two fold:

1. I must address all old files with the 'long' variable and cast
&/or convert each encountered variable.
2. All new files must be treated different than the first files.

Unless I'm missing something, I could 'sprintf' item #1 above into a
'char' variable and with the
new files, I could set a flag indicating the "new" file type and open
the variable accordingly.

If you have a better way of doing things, please send your comments /
suggestions to:

ax...@ix.netcom.com

Thanks,

Steve in Seattle


s...@borg.com

unread,
Oct 17, 1996, 3:00:00 AM10/17/96
to Steven Truax

Steven Truax wrote:
> variable such as '12', I would like to place the value '12a' into this

If you don't need to add too many letters, why not use hexidecimal
notation?

Just a thought,
Rich Ireland

Russell Salsbury

unread,
Oct 20, 1996, 3:00:00 AM10/20/96
to

Watch out for bad implementations of rand()! On SunOS 4.1.3 rand() is
garbage (no, not random garbage). Use lrand48() and company instead.

Ryan russ...@netcom.com


0 new messages