Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ generate a good random seed for psudo random number generators

I am trying to generate a good random seed for a psudo-random number generator. I thought I'd get the expert's opinions. let me know if this is a bad way of doing it or if there are much better ways.

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

unsigned int good_seed()
{
    unsigned int random_seed, random_seed_a, random_seed_b; 
    std::ifstream file ("/dev/random", std::ios::binary);
    if (file.is_open())
    {
        char * memblock;
        int size = sizeof(int);
        memblock = new char [size];
        file.read (memblock, size);
        file.close();
        random_seed_a = int(memblock);
        delete[] memblock;
    }// end if
    else
    {
        random_seed_a = 0;
    }
    random_seed_b = std::time(0);
    random_seed = random_seed_a xor random_seed_b;
    return random_seed;
} // end good_seed()
like image 542
posop Avatar asked Apr 14 '10 20:04

posop


People also ask

What is a good seed for a random number generator?

Many researchers worry about how to choose a random number seed. Some people use an easy-to-remember sequence such as their phone number or the first few digits of pi. Others use long prime numbers such as 937162211.

What is the seed of a pseudorandom number generator?

A random seed (or seed state, or just seed) is a number (or vector) used to initialize a pseudorandom number generator. For a seed to be used in a pseudorandom number generator, it does not need to be random.

What is seed in random number generator C?

In the C Programming Language, the srand function initializes the sequence of pseudo-random numbers generated when the rand function is called.


2 Answers

The code that reads from /dev/random seems wrong: you're C-style casting the address of your character buffer into random_seed_a (plug for C++ casts here) and ignoring anything you actually read from /dev/random (try *reinterpret_cast<int*>(memblock).

/dev/random should already be a good entropy source, so if it's available don't possibly taint the value with any other data and just use it as the seed directly. If there isn't enough data in /dev/random I would just fall back on the time and use that by itself rather than xor'ing it with something.

like image 139
Mark B Avatar answered Oct 15 '22 10:10

Mark B


Good pseudo-random number generators don't need a "good" seed, any seed (that's different from run to run) works equally well.

Using system time directly is fine (and common). Using /dev/random is also fine.

If your pseudo-random number generator isn't good, even picking a "good" seed won't help. Replace it if you can.

Suggestions: Mersenne twister is a pretty well regarded. Here's a precursor which will run on even the most limited of systems.

like image 36
Jon-Eric Avatar answered Oct 15 '22 10:10

Jon-Eric