如何从Xorshift64*(uint64_t)生成[0,1]均匀分布浮点数?
Converting Xorshift64* uint64_t Output to [0,1] Uniform Floats
Hey there! When working with Xorshift64* (and most 64-bit PRNGs), converting the raw uint64_t state to a uniform [0,1] floating-point number relies on leveraging IEEE 754 double-precision format properties—since doubles have 53 bits of mantissa, which aligns nicely with the 64-bit output of your PRNG.
The Most Efficient & Accurate Approach (For [0, 1))
This method avoids division by large constants directly and preserves maximum precision, which is perfect for your cross-platform performance testing:
#include <stdint.h> uint64_t global_state[1]; // Must be initialized to a NON-ZERO value! double xorshift64star_to_uniform() { uint64_t x = global_state[0]; // Xorshift64* core transformation steps x ^= x >> 12; x ^= x << 25; x ^= x >> 27; global_state[0] = x; // Apply the standard star multiplier for Xorshift64* uint64_t prng_output = x * 0x2545F4914F6CDD1DULL; // Convert to [0, 1) double: // Shift right by 11 bits to extract the top 53 bits (64-11=53) // Multiply by 1.0 / 2^53 (9007199254740992 is 2^53) return (prng_output >> 11) * (1.0 / 9007199254740992.0); }
Key Details to Note:
- Why 53 bits? Double-precision floats have exactly 53 bits of significant precision. Using the top 53 bits of the PRNG's output ensures we don't waste entropy or introduce rounding artifacts from lower bits that can't be represented in the float.
- [0, 1) vs [0, 1]: The code above produces values in the half-open interval [0, 1). If you need the closed interval [0, 1], replace the multiplier with
1.0 / 9007199254740991.0(1 divided by 2^53 minus 1). This will rarely produce exactly 1.0, but it meets the closed interval requirement. - Performance: This approach is lightning-fast—no expensive library calls, just bit shifts and a single multiplication. It’s ideal for comparing PRNG performance across Windows and Linux.
Critical Reminder
Never initialize global_state to zero! Xorshift generators will get stuck on zero indefinitely if started with a zero state.
内容的提问来源于stack exchange,提问作者Thadeu Melo
相关产品推荐
相关产品推荐

