Commit 243c3838 authored by deuce's avatar deuce
Browse files

Fix a distribution problem in xp_random() with limits that are not a power

of two.

Essentially, any bits above the next lowest power of two are less likely
to be set.  For example, xp_random(6) would use 3 bits of randomness with
the following distribution:

000 = 0
001 = 1
010 = 2
011 = 3
100 = 4
101 = 5
110 = 0
111 = 1

As you can see, zero and one are twice as likely to occur than 2,3,4, or 5.
parent eb4d2f1c
......@@ -321,9 +321,17 @@ void DLLCALL xp_randomize(void)
int DLLCALL xp_random(int n)
{
#ifdef HAS_RANDOM_FUNC
int curr;
int limit=((1U<<31) / n) * n;
if(n<2)
return(0);
return(random()%n);
while(1) {
curr=random();
if(curr < limit)
return(curr % n);
}
#else
float f=0;
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment