sto@Bonnie.ICS.UCI.EDU (04/27/91)
does anyone know how to generate random numbers in c from X to Y , where X and Y can be postive or negative ? steven to (sto@bonnie.ics.uci.edu)
jhz@cunixa.cc.columbia.edu (Jennifer H. Zemsky) (04/27/91)
sto@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@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. -------------------------------------------------------------------------------
john@newave.UUCP (John A. Weeks III) (04/28/91)
In <9104261022.aa28844@Bonnie.ics.uci.edu> sto@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 ? Assuming that you have a procedure that returns random numbers between 0 and 1, try using n = X + ( random() * ( Y - X ) ). You might want to compute the range somewhere else, and then take the absolute value of it (in case X > Y). -john- -- ============================================================================= John A. Weeks III (612) 942-6969 john@newave.mn.org NeWave Communications ...uunet!tcnet!wd0gol!newave!john