# Output distribution of rand(Float32) and rand(Float64), thread 2

**URL:** <https://discourse.julialang.org/t/output-distribution-of-rand-float32-and-rand-float64-thread-2/105184>\
**Category:** Internals & Design\
**Tags:** float, random\
**Created:** [October 19, 2023, 1:10pm UTC](https://discourse.julialang.org/t/output-distribution-of-rand-float32-and-rand-float64-thread-2/105184 "2023-10-19T13:10:07Z")\
**Posts on this page:** 1\
**Showing post:** 86

<div class="post-metadata">

**Author:** ![Dan](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dan/32/42581_2.png) [@Dan](https://discourse.julialang.org/u/Dan)\
**Post date:** [October 25, 2023, 9:33am UTC](https://discourse.julialang.org/t/output-distribution-of-rand-float32-and-rand-float64-thread-2/105184/86 "2023-10-25T09:33:13Z")

</div>

Simple and fast way to produce `rand(Float32)` values:

```julia
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
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’).

---

_[View the full topic](https://discourse.julialang.org/t/output-distribution-of-rand-float32-and-rand-float64-thread-2/105184)._
