std::uniform_int_distribution isn't random enough

前端 未结 4 1091
面向向阳花
面向向阳花 2021-01-07 15:16

I want to randomly select an integer among n numbers, where n is small (say 5). To do this, I am using std::uniform_int_distribution.

The exact details

相关标签:
4条回答
  • 2021-01-07 15:45

    Try to seed the random engine. Time is a good choice. Read this to get familiar to another ways.

    std::default_random_engine generator( (unsigned int)time(0) );
    

    or you can use std::random_device which tries to produce non-deterministic random numbers

    std::default_random_engine generator( std::random_device{}() ); 
    

    std::random_device is a uniformly-distributed integer random number generator that produces non-deterministic random numbers.

    Note that std::random_device may be implemented in terms of a pseudo-random number engine if a non-deterministic source (e.g. a hardware device) is not available to the implementation.

    It uses a hardware random generator device or generates a pseudo random number. Useful to seed.

    0 讨论(0)
  • 2021-01-07 15:48

    You didn't seed your default_random_engine, so it's using the default, constant, seed.

    0 讨论(0)
  • 2021-01-07 15:48

    As others have mentioned, your main problem is that you're not seeding your engine. I thought I'd address something else since you note that speed and quality is important to you.

    Unlike other engines, default_random_engine makes no guarantees. Do not use it if you have any reasonable requirement. It's only there if you don't know what you're doing and the application of it doesn't really matter. From the standard:

    Remark: The choice of engine type named by this typedef is implementation-defined. [ Note: The implementation may select this type on the basis of performance, size, quality, or any combination of such factors, so as to provide at least acceptable engine behavior for relatively casual, inexpert, and/or lightweight use. Because different implementations may select different underlying engine types, code that uses this typedef need not generate identical sequences across implementations. — end note ]

    A better choice might be mt19937, which has high quality and is very fast.

    0 讨论(0)
  • 2021-01-07 15:57

    As said, I should seed the generator. Notice that the reference does not provide something obvious for a seed.

    The working code is here.

    Notice, that as mentioned in the answers, mt19937 should be used, for better speed and quality.

    Example in first answer here.

    Here is another example, found on the internet, that compiles.

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