PDA

View Full Version : Random No Generator in C/C++

ankurjain
6th July 2006, 10:58
Hi,

How can we generate a random no without using rand() or any other library function in C/C++.

Can somebody give some logic......

TheKedge
6th July 2006, 11:33
You should see "numerical recipies in C/C++". They have several excellent methods. If you're not worried about amazingly random numbers try this (a small excerpt from chapter 7):
#define IA 16807
#define IM 2147483647
#define AM (1.0/IM)
#define IQ 127773
#define IR 2836
float ran0(long *idum)
/*â€œMinimalâ€ random number generator of Park and Miller. Returns a uniform random deviate
between 0.0 and 1.0. Set or reset idum to any integer value (except the unlikely value MASK)to initialize the sequence; idum must not be altered between calls for successive deviates in a sequence./**/
{
long k;
float ans;
*idum ^= MASK; XORing with MASK allows use of zero and other
simple bit patterns for k=(*idum)/IQ; idum.
*idum=IA*(*idum-k*IQ)-IR*k; Compute idum=(IA*idum) % IM without overif
(*idum < 0) *idum += IM; flows by Schrageâ€™s method.
ans=AM*(*idum); Convert idum to a floating result.