Search code examples
random

How the rand() choose a number?


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?


Solution

  • 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