views:

355

answers:

6

Possible Duplicate:
What’s the Right Way to use the rand() Function in C++?

Hi all, I'm trying to set up a random number generation function in c++. Im trying to set it up so that it generates a number between 1 & 500. Right now it returns integers in order according to the system clock, I need TRUE random numbers. Can anyone help?? This is what i have so far:

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main ( )
{
    srand( time (0) );
    int min = 1, max = 500, randNumber;
    randNumber = 1 + rand( ) % 500;
    cout << randNumber << endl;
    system("pause");
    return 0;
} 
A: 

Well, the thing is, generating a random number (what you currently have is a pseudo random number generator) isn't as easy as you think. If you want the numbers to be more "random" you need more entropy. This can be sourced from many different places but unless you are doing tasks the heavily require truly random numbers, what you have here is pretty good.

Sam152
A: 

The fact is there is no such thing as a TRUE random number generator. They all use some form of equation based off something(usually system clock).

Now if you want a random float. well that was solved here

CheesePls
A: 

Boost has the mersenne twister and many others which return "pretty random" numbers.

As others have said though, computers aren't good at random.

jamesj629
A: 

There is no such thing as true random in programming, it all uses pseudo-random number generators. It's a little different on Windows and Linux and .NET (next time you may want to expand the question a bit), but I always make the random seed the time in milliseconds - this ensures at the very least it will be marginally different each and every time you run. I recommend getting the milliseconds from a time_t object, like you have, and don't forget to cast it into something more numeric, like a long.

Steve H.
A: 

On Linux, you can get entropy from /dev/random and use that to seed the random number generator. This is real randomness. The Windows crypto random number API is likely to work similiarly.

/dev/random collects randomness from various I/O activities.

bmargulies
A: 

As others pointed, you should search SO first as it's been answered.

Just check Boost.Random and here you have quick example of how to generate but pseudo-random numbers from the range you need:

#include <iostream>
#include <boost/random.hpp>

int main()
{
    typedef boost::minstd_rand rng_type;
    typedef boost::uniform_smallint<int> dist_type;
    typedef boost::variate_generator<rng_type&, dist_type> generator_type;

    // distribution maps from 1 to 500
    dist_type dist(1, 500);
    rng_type generator;
    generator_type gen(generator, dist);

    // print 5 values
    for (int i = 0; i < 5; ++i)
        std:: cout << gen() << std::endl;

    return 0;
}
mloskot