delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/02/02/02:00:27

From: "A. Sinan Unur" <sinan DOT unur AT cornell DOT edu>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: random number in range
Date: Sun, 01 Feb 1998 19:48:37 -0500
Organization: Cornell University (http://www.cornell.edu/)
Lines: 28
Sender: asu1 AT cornell DOT edu (Verified)
Message-ID: <34D517E5.13D35D9@cornell.edu>
References: <34D50550 DOT 48ED AT quantum DOT de>
NNTP-Posting-Host: cu-dialup-1824.cit.cornell.edu
Mime-Version: 1.0
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

Tom Chojnacki wrote:
> A little problem:
> how can I get random number from a given range.
> Is the following solution efficient or maybe there is any ready-made
> function ?
> 
> long rnd(long low, long high)
> {
> long r;
> 
>   srandom((int)time(0));
>   while (((r = random()) < low) || (r > high))
>     ;
>   return r;
> }

(long)((high-low)*(((double)rand())/(RAND_MAX+1.0))+ (double) low)

incidentally, seeding the random number generator before each call would
result in _LESS_ "randomness" rather than more. seed it once.
-- 
----------------------------------------------------------------------
A. Sinan Unur
Department of Policy Analysis and Management, College of Human Ecology,
Cornell University, Ithaca, NY 14853, USA

mailto:sinan DOT unur AT cornell DOT edu
http://www.people.cornell.edu/pages/asu1/

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019