Generating random numbers effectively

后端 未结 5 1389
故里飘歌
故里飘歌 2021-01-23 23:16

How do you generate random numbers effectively?
Every time a random number program boots up, it starts spitting same numbers as before. (I guess because of quasi nature of

5条回答
  •  星月不相逢
    2021-01-23 23:46

    You can use a chaotic map to generate random numbers. The C++ code below (GenRandRea) returns a vector of random number using the so-called "Tent map" (https://www.wikiwand.com/en/Tent_map). The seed is an integer that is used to generate x (as a number between 0. and 1.) as input of the iterative map. Diferent seeds will generate different sequences.

    vector GenRandRea(unsigned seed, int VecDim){
    double x, y, f;
    vector retval;
    
    x = 0.5*(abs(sin((double)seed)) + abs(cos((double)seed)));
    
    for (int i = 0; i<(tentmap_delay + VecDim); i++) {
        if ((x >= 0.) && (x <= 0.5)) {
            f = 2 * tentmap_r * x;
        }
        else {
            f = 2 * tentmap_r * (1. - x);
        }
    
        if (i>=tentmap_delay) {
            y = (x*tentmap_const) - (int)(x*tentmap_const);
            retval.push_back(y);
        }
        x = f;
    }
    return retval;
    

    }

    with

    const double tentmap_r = 0.75; //parameter for the tent map
    const int tentmap_delay = 50; /*number of interactions in the tent map 
                                  allowing for sorting */
    const double tentmap_const = 1.e6; //constant for the tent map
    

    VecDim is the output vector dimension. The ideia is to iterate at least (tentmap_delay + VecDim) turns and write the result in retval (a vector of doubles).

    To use this code:

    vector val;
    
    val = GenRandRea(2, 10);
    for (int kk=0; kk<10;kk++){
        cout << setprecision(9) << val[kk] << endl;
    }
    

    which will for example produce:

    0.767902586 0.848146121 0.727780818 0.408328773 0.88750684 0.83126026 0.253109609 0.620335586 0.569496621 0.145755069

    Regards!

提交回复
热议问题