delorie.com/archives/browse.cgi   search  
Mail Archives: cygwin/1998/01/16/14:39:52

From: kkont AT estia DOT iit DOT nrcps DOT ariadne-t DOT gr (Kimon Kontovasilis)
Subject: Re: about pseudo-random numbers
16 Jan 1998 14:39:52 -0800 :
Message-ID: <9801151527.AA02734.cygnus.gnu-win32@estia.iit.nrcps.ariadne-t.gr>
References: <Pine DOT LNX DOT 3 DOT 96 DOT 980113114251 DOT 1703C-100000 AT pc66>
Mime-Version: 1.0
To: c9707059 AT cca DOT fc DOT up DOT pt (Valter EOR Santos)
Cc: gnu-win32 AT cygnus DOT com

> 
>   Hi!
>   I am a newby in this mailing list...
>   I am generate a program code that need random number generation...
>   My question is if there is any way to make a limit in the random
> generation. In the Turbo Borland C++ i have the unit random(int limit)
> that produces numbers between 0 and limit. In the gnu, or other linux
> compiler i only have the rand() or srand() units that produces numbers
> between 0 and a pre-defined random_limit variable MAX_RAND (or something
> like that). How i can generate code for resolving my problem???
> 
> _________________________
> Valter Santos
> <c9707059 AT cca DOT fc DOT up DOT pt>
> 

The following simple solution works in most cases and preserves the statistical
properties of the standard rand() up to double precision conversions.

	#include <stdlib.h>

	int range_rand(int limit)
	{
		return (((double) rand() / RAND_MAX) * limit);
	}

It is important to have the division performed in double precision *before*
multiplying by limit and returning as an integer.

As is, the routine will return values between 0 and limit-1 inclusive. Should
you want values from 1 to limit (or offset by any other number, for that
matter), save the expression returned above to an integer (or apply a cast)
and return the result plus the offset.

Initializing (or re-initializing) the seed, is obviously done with the
standard srand() routine.


Regards,

Kimon Kontovasilis.
-----------------------
Dr. Kimon Kontovasilis,
National Center for Scientific Research "Demokritos",
Inst. for Informatics & Telecommunications.
-
For help on using this list (especially unsubscribing), send a message to
"gnu-win32-request AT cygnus DOT com" with one line of text: "help".

- Raw text -


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