Skip to main content

Module division

Module division 

Source
Expand description

Shift-and-scale conversion.

The technique used by most language runtimes and libraries: take as many bits as the target type has of precision (53 for f64, 24 for f32) and scale them by the corresponding power of two. Every arithmetic step is exact, so the result is equispaced: the 2⁵³ multiples of 2⁻⁵³ in [0 . . 1) for f64, each with probability 2⁻⁵³.

This is by far the cheapest conversion, but most representable floats never occur: no nonzero value below 2⁻⁵³ can appear.

Note that using a larger number of bits (e.g., Go used 63) leads to a nonuniform distribution because of the round-to-even of IEEE 754.

Functions§

f32_24bits
Returns a random f32 uniform on the 2²⁴ multiples of 2⁻²⁴ in [0 . . 1): the top 24 bits of one word, scaled by 2⁻²⁴.
f64_53bits
Returns a random f64 uniform on the 2⁵³ multiples of 2⁻⁵³ in [0 . . 1): the top 53 bits of one word, scaled by 2⁻⁵³.