Home

C++ Better Random Numbers

This only works on C++ version 11 and forwards.

You need to include random

#include <random>

Then try the following for size...

    random_device MyRandomDevice;
    default_random_engine MyDefaultRandomEngine(MyRandomDevice());
    uniform_int_distribution<long> MyDistribution(0, 10000000);

    for (int i = 0; i < 100; i++) {
        cout << MyDistribution(MyDefaultRandomEngine) << endl;
    }

So obviously including random adds a selection of code hidden in the deep and murky depths of C++ version 11 somewhere. This code does the randoming so you don't have to. ALWAYS note that computer random is pseudo-random. This will be fine for a simple game or pretend dice but you need to do a lot more work if you're working on security dependent programs.

As far as I can work out we create a random device instance and a random engine instance. The distribution is declared and set with "from" and "to" values. We then call the distribution with the engine that uses the device... Complicated? Much, but not intolerably so. Be much nicer to have long x = MakeRandomNumber(from, to). You could of course write this...

long MakeRandomNumber(long MyStart, long MyEnd) {
    random_device MyRandomDevice;
    default_random_engine MyDefaultRandomEngine(MyRandomDevice());
    uniform_int_distribution<long> MyDistribution(MyStart, MyEnd);

    return MyDistribution(MyDefaultRandomEngine);
}

int main()
{
    for (int i = 0; i < 100; i++) {
        cout << MakeRandomNumber(10, 1000) << endl;
    }
}

 

Reader's Comments

Post Your Comment Posts/Links Rules

Name

Comment

Add a RELEVANT link (not required)

Upload an image (not required)

No uploaded image
Real person number
Please enter the above number below




Home
Admin Ren's Biking Blog