vendredi 5 août 2022

Seeding a random number generator with a double and having it generate the same sequence on 64 or 32 bit platforms

I have a problem where I really need to seed a random number generator with a double value. The generated random number should be between {min, max}. My current solution is

double map(double in, double min, double max){
    size_t seed = std::hash<double>()(in);
    unsigned int seed2 = (unsigned int)(seed >> (sizeof(size_t)-sizeof(unsigned int)));
    std::mt19937 gen{seed2}; 
    std::uniform_real_distribution<double> dis(min, max);
    return dis(gen);
}

The problem with the above is that hash to size_t will not be the same on all platforms. therefore expect the result will different on various platforms. Can this algorithm be altered to generate the same output for the same input on all platforms whilst still being pseudorandom.

Example at https://godbolt.org/z/rfT3ajbbo

On 64 bit gcc build the output is

0.9223
0.0733052
0.0168922
0.993303
0.330736

on 32 bit gcc build the output is

0.121904
0.188877
0.839134
0.984475
0.171036

Aucun commentaire:

Enregistrer un commentaire