Better random algorithm?

I am making a game in C ++, and it involves filling plates with arbitrary logical values ​​(yes or no), regardless of whether it is yes or no, it is determined rand() % 1. He does not feel very random.

I use srandc ctimeat startup, but it looks like the same patterns appear.

Are there any algorithms that will create very random numbers? Or any suggestions on how I could improve rand()?

+5
source share
14 answers

True randomness often does not seem very random. Expect to see odd runs.

, , , , . Numerical Recipes C:

1 10, , ,
j = 1 + (int) (10.0 * (rand() / (RAND_MAX + 1.0)));
j = 1 + (rand() % 10);
( ).

, RNG . Xorshift - . C, .

+22

.
% 2, .

, .
.

bool  tile = rand() > (RAND_MAX / 2);
+8

, , PRNG , - , rand(). , . , , . , 14 31 .

, rand(), ( rand(), , , RAND_MAX). , RAND_MAX 32768, 15 . , RAND_MAX , , . , Microsoft CRT

x n + 1= x n & middot; 214013 + 2531011

16 15 . , . , RAND_MAX 2 31 ( , , 16 24 , ).

, , rand() rand() % 2.

+4

, , . , .

+3

. Hiroshima Uni . ( , -!)

, :

  • "" .
  • ints , , , .

.

+2

- . .

+1

, .

.

+1

++ 11 Mersenne tittie twister algorothm. cppreference.com:

#include <random>
#include <iostream>

int main()
{
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(1, 6);

    for (int n=0; n<10; ++n)
        std::cout << dis(gen) << ' ';
    std::cout << '\n';
}

, . ; .

Well equidistributed long-period linear; .

+1

, , , if(rand() % 50==0) .

0

, . - . 28- :

(rand() >> 13) % 2
0

. , . Scheme .

0

, . - .

, , . .

-1

Also, if you reboot too quickly, you will get the exact number. Personally, I use a class that updates the seed only when the time has changed.

-2
source

All Articles