Skip to content

Commit

Permalink
Fix thread local rng implementation in C so it's correctly unbiased a…
Browse files Browse the repository at this point in the history
…nd actually random.
  • Loading branch information
gbaraldi committed Aug 15, 2024
1 parent 304ed25 commit d84d3ad
Showing 1 changed file with 21 additions and 8 deletions.
29 changes: 21 additions & 8 deletions src/julia_internal.h
Original file line number Diff line number Diff line change
Expand Up @@ -1308,18 +1308,31 @@ JL_DLLEXPORT size_t jl_maxrss(void);

STATIC_INLINE uint64_t cong(uint64_t max, uint64_t *seed) JL_NOTSAFEPOINT
{
if (max == 0)
if (max < 2)
return 0;
uint64_t mask = ~(uint64_t)0;
--max;
mask >>= __builtin_clzll(max|1);
uint64_t x;
int zeros = __builtin_clzll(max);
int bits = CHAR_BIT * sizeof(uint64_t) - zeros;
mask = mask >> zeros;
do {
*seed = 69069 * (*seed) + 362437;
x = *seed & mask;
} while (x > max);
return x;
uint64_t value = 69069 * (*seed) + 362437;
*seed = value;
uint64_t x = value & mask;
if (x < max) {
return x;
}
int bits_left = zeros;
while (bits_left >= bits) {
value >>= bits;
x = value & mask;
if (x < max) {
return x;
}
bits_left -= bits;
}
} while (1);
}

JL_DLLEXPORT uint64_t jl_rand(void) JL_NOTSAFEPOINT;
JL_DLLEXPORT void jl_srand(uint64_t) JL_NOTSAFEPOINT;
JL_DLLEXPORT void jl_init_rand(void);
Expand Down

0 comments on commit d84d3ad

Please sign in to comment.