extremely inefficient but works....?

Ok so what if I took rand and instead of modding it by the number I want and adding one, I just added the result of a test to see whether rand() is bigger than half or less than half of the maximum number you can get of that type? I know it’s the most inefficient thing ever, but still I could work, right? Sorry I mean it might make a uniform distribution.

1
2
3
4
5
6
7
8
9
#include <cstdlib>

size_t udist(size_t maxVal){
  size_t res = 0;
  for(size_t i = 0;i < maxVal;i++){
    res += (int)( (RAND_MAX/2) > rand() );
  }
  return res;
}
Last edited on
That's not a uniform distribution.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;

const int Size = 10;
const int Reps = 1000;

size_t udist(size_t maxVal) {
    size_t res = 0;
    for (size_t i = 0; i < maxVal - 1; ++i)
        res += rand() <= RAND_MAX / 2;
    return res;
}

int main() {
    int a[Size] {};
    for (int i = 0; i < Reps; ++i)
        ++a[udist(Size)];
    for (int i = 0; i < Size; ++i)
        cout << setw(3) << i << ": " << setw(5) << a[i] << '\n';
}



  0:     2
  1:    16
  2:    64
  3:   151
  4:   255
  5:   267
  6:   164
  7:    64
  8:    15
  9:     2

Last edited on
Darn. Too bad.
Of course, rand() % n is not typically uniform either.
They are not uniform for different reasons.

rand() % N is never uniform...
...unless N is (RAND_MAX + 1), which is a whole can of worms in itself.
Really? Wouldn't cases where both RAND_MAX + 1 and N are powers of two (and 2 <= N <= RAND_MAX as usual) produce a uniform distribution?
RAND_MAX is always an odd number of the form (2n - 1), making a uniform modulus impossible.
But RAND_MAX closes the interval [0, RAND_MAX] comprising the possible values of rand(), so wouldn't every bit in the result be uniformly random?

(first sentence: https://en.cppreference.com/w/cpp/numeric/random/rand )
Last edited on
Yeah you can do bit masking to get """uniform"""" distributions, e.g. mask with (RAND_MAX + 1) / 2^m. In other words, "rand() % n is not uniformly distributed unless RAND_MAX+1 happens to be divisible by n."
But rand isn't even guaranteed to be uniform to begin with.
Last edited on
Topic archived. No new replies allowed.