Article View: comp.sys.amiga.tech
Article #7273Re: rand() within a range.
From: Dan Barrett
Date: Fri, 07 Dec 1990 21:41
Date: Fri, 07 Dec 1990 21:41
47 lines
2036 bytes
2036 bytes
I tried e-mail but it bounced.
In article <666@sheoak.bcae.oz> 737104@sheoak.bcae.oz (David Thiele) writes:
>Is there a way to generate random numbers within a certain range in
>Lattice C??
It can be done in ANY language -- there is a mathematical formula
for it. All you need is a function Rand() that returns a random real number
between 0 and 1 (not including 1). This is commonly supplied by your
compiler company.
To generate a random integer between integers A and B, with A < B:
(1) Figure out the distance between A and B:
distance = B - A + 1;
(2) Multiply a random number by the distance, and truncate the
remainder. This gives you a random integer between 0 and
(distance - 1):
first = floor(distance * Rand());
(3) Now increase this number by A, to give you an integer between
A and (A + distance - 1). But remember:
A + distance - 1
= A + (B - A + 1) - 1
= B
So you have a random integer between A and B:
answer = first + A;
Here is the final formula:
answer = floor((B - A + 1) * Rand()) + A;
Dan
//////////////////////////////////////\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
| Dan Barrett - Systems Administrator, Computer Science Department |
| The Johns Hopkins University, 34th and Charles Sts., Baltimore, MD 21218 |
| INTERNET: barrett@cs.jhu.edu | |
| COMPUSERVE: >internet:barrett@cs.jhu.edu | UUCP: barrett@jhunix.UUCP |
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\/////////////////////////////////////
Technical Details
Message-ID:
<7083@jhunix.HCF.JHU.EDU>Path:
arc1-ca.pugleaf.net!utzoo!utgpu!news-server.csri.toronto.edu!rutgers!usc!zaphod.mps.ohio-state.edu!uakari.primate.wisc.edu!aplcen!jhunix!barrettReferences:
<666@sheoak.bcae.oz>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!utzoo!utgpu!news-server.csri.toronto.edu!rutgers!usc!zaphod.mps.ohio-state.edu!uakari.primate.wisc.edu!aplcen!jhunix!barrett From: barrett@jhunix.HCF.JHU.EDU (Dan Barrett) Newsgroups: comp.sys.amiga.tech Subject: Re: rand() within a range. Message-ID: <7083@jhunix.HCF.JHU.EDU> Date: 7 Dec 90 21:41:28 GMT References: <666@sheoak.bcae.oz> Organization: The Johns Hopkins University - HCF Lines: 47