Use of qsrand, random method that is not random

后端 未结 7 2647
误落风尘
误落风尘 2021-02-19 00:12

I\'m having a strange problem here, and I can\'t manage to find a good explanation to it, so I thought of asking you guys :

Consider the following method :



        
相关标签:
7条回答
  • 2021-02-19 00:27

    I've found the same action and solved it by using rand() instead the srand().

    But I use it for checking my application. It just working in the cicle, so I don't need to look for it updates.

    But if you going to do some king of game, it isn't a good way, because your randomizing will be the same.

    0 讨论(0)
  • 2021-02-19 00:30

    If you call the qsrand Qt function to initialize the seed, you must call the qrand Qt function to generate a random number, not the rand function from the standard library. the seed initialization for the rand function is srand. Sorry for the dig up.

    0 讨论(0)
  • 2021-02-19 00:35

    Two problems:

    1 As others have pointed out, the generator is being seed multiple times.

    2 This is not a very good method to generate random numbers within a given range. (In fact it's very very bad for most generators )

    You are assuming that the low-order bits from the generator are uniformly distributed . This is not the case with most generators. In most generators the randomness occurs in the high order bits.

    By using the remainder after divisions you are in effect throwing out the randomness.

    You should scale using multiplication and division. Not using the modulo operator. eg

    my_number= start_required + ( generator_output * range_required)/generator_maximum;

    if generator_output is in [0, generator_maximum] my_number will be in [start_required , start_required + range_required]

    0 讨论(0)
  • 2021-02-19 00:38

    If you make the call fast enough the value of QTime::currentTime().msec() will not change, and you're basically re-seeding qsrand with the same seed, causing the next random number generated to be the same as the prior one.

    0 讨论(0)
  • 2021-02-19 00:40

    modern Qt c++ 11

    #include <random>
    #include "QDateTime"
    
    int getRand(int min, int max){
        unsigned int ms = static_cast<unsigned>(QDateTime::currentMSecsSinceEpoch());
        std::mt19937 gen(ms);
        std::uniform_int_distribution<> uid(min, max);    
        return uid(gen);
    }
    
    0 讨论(0)
  • 2021-02-19 00:47

    What you see is the effect of pseudo-randomness. You seed it with the time once, and it generates a sequence of numbers. Since you are pulling a series of random numbers very quickly after each other, you are re-seeding the randomizer with the same number until the next millisecond. And while a millisecond seems like a short time, consider the amount of calculations you're doing in that time.

    0 讨论(0)
提交回复
热议问题