It being uniform maybe the key takeaway considering in a perfect world the odds of 50/50 should be even. I'm thinking using the seed(time(0)) rand()%2 etc would be the way to go to get some more randomness out of it. I'm actually kinda curious what the results would be now. |
Actually, the
probability of getting "
0" (false) or "
1" (true) should be exactly 50%. But this does
not mean that, in an actual
sample, you get
exactly 50%
0's and
exactly 50%
1's. Even if you generate 1000 values (coin flips) with a "perfect" RNG, then it is absolutely possible to get 1000 times
0 in a row – it's just
not very likely ;-)
In fact, if in
every sample you generate, there always are
exactly 50%
0's and
exactly 50%
1's, then this would indicate that your RNG is "broken", because that's
not what we'd expect from "true" random coin flips.
Note that, in general,
rand()
is
not a very good RNG. And here "not good" means it can easily be distinguished from "true" random numbers by statistical tests. Even worse, by
rand() % 2
you only take the
least-significant bit of each number generated by the RNG. For many RNG algorithms, the least-significant bit may
not be evenly distributed! That's why you probably should be using
std::uniform_int_distribution<>(0,1)
, together with a "good" RNG algorithm, such as
std::mt19937
(Mersenne Twister), and seeded from
std::random_device
.
1 2 3 4 5 6 7 8 9 10 11 12 13
|
#include <iostream>
#include <functional>
#include <random>
int main()
{
std::random_device seed;
auto coin_flip = std::bind(std::uniform_int_distribution<int>(0, 1), std::mt19937(seed()));
for (int i = 0; i < 1000; ++i)
{
std::cout << coin_flip() << std::endl;
}
}
|