1

Possible Duplicate:
How does rand() work? Does it have certain tendencies? Is there something better to use?

I'm not sure when the rand() function or similar in any programming language returns a value totally "logical". Because they are not based on time, hours, days or something I wonder how he chooses the number. One could answer me?

Thanks, Bruno Alano.

Community
  • 1
  • 1
Bruno Alano
  • 643
  • 1
  • 11
  • 21
  • Often it uses a linear congruential PRNG, which means that there's a state number `s` (which you can seed to some initial value), and at each turn you compute `s = m * s + b` for some fixed constants `m` and `c`. If you pick the constants well, the resulting numbers are pretty "random" looking. There are many other algorithms, of course, but this one is particularly simple and easy. – Kerrek SB Jul 26 '11 at 22:58

4 Answers4

2

It depends on the algorthmn. Wikipedia has a summary of one way of computationally creating a 'random number' http://en.wikipedia.org/wiki/Random_number_generation

m_w = <choose-initializer>;    /* must not be zero */
m_z = <choose-initializer>;    /* must not be zero */

uint get_random()
{
   m_z = 36969 * (m_z & 65535) + (m_z >> 16);
   m_w = 18000 * (m_w & 65535) + (m_w >> 16);
   return (m_z << 16) + m_w;  /* 32-bit result */
}

You can now buy hardware random number generators that produce better random numbers

JonAlb
  • 1,702
  • 10
  • 14
1

Actually, most implementations of rand are based on time in some way. Typically, when creating a random number, you can pass in a seed. The same seed will produce the same string of random-looking numbers. If no seed is passed in, most implementations create a seed from the current system time.

colithium
  • 10,269
  • 5
  • 42
  • 57
0

It depends upon the implementation of the library you are linking. POSIX.1-2001 gives the following example of an implementation of rand() and srand(), possibly useful when one needs the same sequence on two different machines.

static unsigned long next = 1;
/* RAND_MAX assumed to be 32767 */
int rand(void) {
    next = next * 1103515245 + 12345;
    return((unsigned)(next/65536) % 32768);
}
void srand(unsigned seed) {
     next = seed;
}
Manlio
  • 10,768
  • 9
  • 50
  • 79
0

It depends on the algorithm implementation. However must of the implementation are deterministic such as an LCG algorithm.

The period of this deterministic algorithms depends on the values chosen for the formula, the seed itself is usually a timestamp + constant. You can find the LCG implementations for some languages in this wikipedia page:

LCG Algorithm

Non deterministic number generators such as SecureRandom in Java use an algorithm coupled with hardware to try to generate truly random numbers

Oscar Gomez
  • 18,436
  • 13
  • 85
  • 118