random numbers in c
Jennifer H. Zemsky
jhz at cunixa.cc.columbia.edu
Sun Apr 28 00:26:20 AEST 1991
sto at Bonnie.ICS.UCI.EDU writes:
> does anyone know how to generate random numbers in c from X to
>Y , where X and Y can be postive or negative ?
i assume you want a random integer on the range [X,Y]
this is a routine that i use. it works for me.
this should work for positive and/or negative values of high and low.
if you want non-integers, chagne the value of modsize to high-low
and remove the (int) cast from the return line. snafu: the range
for non-integers is [low,high).
i don't think that you need any extra #include libraries... maybe math.h ?
-----cut---here-----
int Random (low, high)
int low, high;
{
int modsize = high-low+1;
double valu;
valu = drand48(); /* [0,1) */
valu *= modsize; /* [0, modsize)*/
valu += low; /* [low, high+1)*/
return ((int) valu); /*[low, high]*/
}
-----cut---here-----
--hymie
jhz at cunixa.cc.columbia.edu
-------------------------------------------------------------------------------
note: the above information, knowledge, etc. is offered only on an
as-is basis. the author takes no responsibility for innacuracy or for
problems caused by implementing said information. veracity is not
guaranteed. corrections welcome.
-------------------------------------------------------------------------------
More information about the Comp.lang.c
mailing list