ran2 giving nonrandom results ... why?


vonkorff
08-06-2008, 10:41 PM
I ran the following code attempting to produce a random integer between 0 and 4 294 967 295 = 256^4 - 1. On my system, a long long is 8 bytes, so there should be plenty of room to hold the value.

I multiplied ran2 by 256^4 - 1. But the number I get by doing this is slightly more frequently even (by 1%) than it is odd! The code below checks the last hex digit of each integer. Can other people reproduce this behavior?

#include<cstdio>
#include<cstring>
#include<ctime>
#include<cstdlib>
#include "ran.h"

int main() {

int idum = -time(NULL);

int arr[16];
for(int i = 0; i < 16; i++)
arr[i] = 0;

for(long long i = 0; i < 8000000; i++) {
double fraction = ran2(idum);
long long max_Lint = (long long) 256 * (long long) 256 * (long long) 256 * (long long) 256 - 1;
long long Lint = (long long) ((double)max_Lint * fraction);
arr[Lint & 15]++;
}

for(int i = 0; i < 16; i++)
printf("arr[%d] = %d\n", i, arr[i]);
}

vonkorff
08-07-2008, 11:05 AM
Oops -- somehow I ended up with a double post. Can't delete a thread ... sorry.

vonkorff
08-07-2008, 02:10 PM
Okay -- the answer appears to be that ran2 doesn't have enough precision to do what I wanted it to do ... it starts with a random 4 byte positive signed int to make its double, so it can't make a random 4 byte unsigned int. If it tries to do so, it will only be able to output every other integer.