Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 24 additions & 8 deletions src/julia_internal.h
Original file line number Diff line number Diff line change
Expand Up @@ -1306,20 +1306,36 @@ JL_DLLEXPORT size_t jl_maxrss(void);
// congruential random number generator
// for a small amount of thread-local randomness

//TODO: utilize https://github.com/openssl/openssl/blob/master/crypto/rand/rand_uniform.c#L13-L99
// for better performance, it does however require making users expect a 32bit random number.

STATIC_INLINE uint64_t cong(uint64_t max, uint64_t *seed) JL_NOTSAFEPOINT
{
if (max == 0)
if (max < 2)
return 0;
Comment on lines +1315 to 1316
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems biased against returning 1

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The old rng is also broken here, which is fun. But basically the issue is that it's a [0, n) interval. So to get 0 and 1 you pass in 2.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Though I'll see if anyone that's using this is actually checking that.

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