I use this random generator for numbers but it seems that this generator isn´t really random because it seems to generate the same "Random" sequence chain every time I restart the application.

Is there a better way to generate random numbers than this, that is more random ?

for( int i = 0; i < 200; i++ )
{
				 
	int RandomNum = rand() % 100;
			 
}

Dani AI

Generated

Short guide that builds on what , and already said.

rand() is a simple pseudo‑random generator and, by default, produces the same sequence each run unless seeded. For real improvement in quality and control, prefer the C++11 <random> facilities: pick a modern engine (for example, Mersenne Twister) and a distribution object rather than using modulus on a single integer generator. That avoids range bias and gives you reproducible or non‑reproducible behavior depending on how you seed.

A minimal pattern to use everywhere in your program (seed once, reuse the engine) looks like this:

#include <random>

std::random_device rd;
std::mt19937 gen(rd());            // or std::mt19937 gen(12345); for reproducible runs
std::uniform_int_distribution<> d(0, 99);
int RandomNum = d(gen);

Practical tips and cautions:

  • Seed once at program start. Don’t call srand()/reseed inside a tight loop — that usually makes things worse. If you need repeatable tests, use a fixed seed and log it so you can recreate the sequence.
  • Avoid rand() % n because it can bias results when the generator range isn’t a multiple of n. std::uniform_int_distribution avoids that for you.
  • RAND_MAX can be small on some systems; modern engines offer much larger periods and better statistical properties.
  • If you need cryptographically secure randomness (passwords, keys), use the OS crypto RNG or a vetted library (don’t roll your own). std::random_device is implementation dependent; it may be non‑deterministic on some platforms but deterministic on others.
  • For multithreaded code, give each thread its own generator (thread_local) or protect a shared one with a lock.

These changes keep debugging predictable when you want it, and improve randomness quality when you need it.

Recommended Answers

All 5 Replies

1.Seed using srand()
Visit http://www.daniweb.com/forums/thread1769.html
2.Computer can only generate pseudo random number. Understand the difference. Please visit

There are libraries that generate better pseudo-random numbers. The rand() function in the standard libraries is - as you've seen - a poor substitute if you really need random numbers. I ended up searching Google last time I needed a random number generator. Someone on here may have more info though. If all else fails, try looking for "stochastic library, random number generator library" or "pseudo-random number generator". I can't remember what I searched for (it was a couple of years ago, sorry)

wow, thank you for these advices, I will googling around for this and also check these links to see what I can find and do...

Regards..

>but it seems that this generator isn´t really random
Any deterministic method for generating random numbers won't be "really" random. That's why they're called pseudorandom numbers. They're sufficiently patternless to appear random for many purposes. "Real" random numbers only come from truly random real world sources, such as the decay of a radioactive material or atmospheric noise.

>because it seems to generate the same "Random"
>sequence chain every time I restart the application
That's a good thing. Imagine trying to debug your program when you can't reproduce the same sequence, ever. The seed for rand defaults to 1, and you can call srand to change it. Here's a demo of seeding based on the current time:

#include <climits>
#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <iostream>

namespace JSW {
    using namespace std;

    // Replaces the conventional but non-portable
    //    (unsigned)time(NULL)
    // as a seed for srand with a portable and
    // equivalent quality seed generator based 
    // on the current time
    unsigned time_seed()
    {
        time_t now = time ( 0 );
        unsigned char *p = (unsigned char *)&now;
        unsigned seed = 0;

        for ( size_t i = 0; i < sizeof now; i++ )
            seed = seed * ( UCHAR_MAX + 2U ) + p[i];

        return seed;
    }

    // Just for output formatting
    size_t digits ( int value )
    {
        if ( value == 0 )
            return 1;

        size_t n = 0;

        for ( n = 0; value != 0; n++ )
            value /= 10;

        return n;
    }

    void sleep ( double seconds )
    {
        // This busy-wait method is not recommended, but 
        // it's portable until you try fractions of a second
        time_t start = time ( 0 );

        while ( difftime ( time ( 0 ), start ) < seconds )
            ;
    }
}

int main()
{
    using namespace std;

    const int batches = 10;
    const int numbers = 10;

    // Generate M batches of N random 
    // numbers, reseeding before each batch
    for ( int i = 0; i < batches; i++ ) {
        srand ( JSW::time_seed() );

        for ( int j = 0; j < numbers; j++ )
            cout<< setw ( JSW::digits ( RAND_MAX ) ) << rand() <<' ';

        cout<<'\n';
        JSW::sleep ( 2 );
    }
}
commented: Props for repeating your seeding. +18

Thanks Narue and others. I think I will go with the srand() it seems to to do the nessecary randomness for this purpose.
I came up with this example:

#include <ctime>

srand((unsigned)time(nullptr)); 
int RandomNum = 0;

for( int i = 0; i < 200; i++ ) 
{ 
     RandomNum = rand() % 100; 
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.