Path: utzoo!utgpu!news-server.csri.toronto.edu!bonnie.concordia.ca!uunet!stanford.edu!rutgers!cunixf.cc.columbia.edu!cunixa.cc.columbia.edu!jhz From: jhz@cunixa.cc.columbia.edu (Jennifer H. Zemsky) Newsgroups: comp.lang.c Subject: Re: random numbers in c Message-ID: <1991Apr27.142620.6859@cunixf.cc.columbia.edu> Date: 27 Apr 91 14:26:20 GMT References: <9104261022.aa28844@Bonnie.ics.uci.edu> Sender: usenet@cunixf.cc.columbia.edu (The Network News) Reply-To: jhz@cunixa.cc.columbia.edu (Jennifer H. Zemsky) Organization: Columbia University Lines: 37 Nntp-Posting-Host: cunixa.cc.columbia.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 ? 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. -------------------------------------------------------------------------------