how random is ( rand() > rand() ? true : false )

1.4k Views Asked by At

I was going to post this question on SO but I suspect it needs mathematical treatment. I need to make a decision(True or False) while running a simulation and I decided that this particular decision should be random.
At first I compared a random value with a static value (0.5) but I soon realized that I am getting 50% True, and 50% False. (So I can use 0.75 if I want 75% True and 25% False)
But I didn't want this particular distribution. So I wrote a function which compared a random value (between 0 and 1) with another random value.
[I have taken care of seeding the random generator with microseconds so IMO 'seed'ing part is not the problem.]
The function looks like

getResponse() {
    rand1 = rand();
    rand2 = rand();
    if ( rand1 > rand2 )
        return True;
    else
        return False;
}

My question is how random is the outcome of this function?
Here is the outcome (1=True 0=False) for 100 calls to function
0001101001010100110011100100011001010111101101100110010100100001110111110110001101101110000111010100
Do you see any pattern? Should there be any pattern? What happens if I reseed the random generator after say every 3rd call?
If this approach doesn't look right, can you suggest any other approach?


EDIT

I have realized my mistake of confusing pattern and distribution. I apologize for the same. I must understand first what distribution I want . Unless that is taken care of, I can not make any progress.
After going through comments and suggestions, I feel that a functional approach will either require keeping track of past results or decide on the distribution of outcome.
On second thoughts I decided neither is necessary if we get a constantly changing variable into the picture.
Enter microtime() which returns microseconds after current second.
Too bad I can't answer till next 8 hours, so I am excusing myself to type it here.

getResponse() {
    return ( microtime()*1000000 % 2 ) ? True : False;
}
1

There are 1 best solutions below

11
On BEST ANSWER

Use http://www.random.org/clients/ or
http://en.wikipedia.org/wiki/Hardware_random_number_generator.

When there have been m falses and n trues,
return false with probability (n+1)/(m+1+n+1) and true with probability (m+1)/(m+1+n+1).