Simple and fast way to produce rand(Float32)
values:
function randf32()
u = rand(UInt64)
lz = leading_zeros(u)
res = (UInt32(126-lz)<<23) | UInt32((u ⊻ ((UInt64(0x1) << (63-lz)))) >> max(0,62-lz-22))
return reinterpret(Float32, res)
end
This method is fast:
julia> @btime randf32()
3.077 ns (0 allocations: 0 bytes)
0.03150859f0
and possibly quite SIMD friendly.
Also, obviously no rounding shenanigens and a (0,1) range. The code itself might be beautified a bit, and at a cost of a conditional, the near zero values can be fixed (adding subnormals/zero for ‘perfection’).