# 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:** 77

<div class="post-metadata">

**Author:** ![dlakelan](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dlakelan/32/8491_2.png) [@dlakelan](https://discourse.julialang.org/u/dlakelan)\
**Post date:** [October 24, 2023, 11:31pm UTC](https://discourse.julialang.org/t/output-distribution-of-rand-float32-and-rand-float64-thread-2/105184/77 "2023-10-24T23:31:31Z")

</div>

Ok, I had some time to think about the problem and came up with this, though I don’t think it’s really “better” than Float32(rand(Float64))

```julia
function rand32float()
   c = -1.0
   while c <0.0 || c >= 1.0
     i = rand(UInt64)
     a = Float32(i >> 32)/2^(32)
     b = Float32(mod(i,2^32)/2^32)
     c = (a + b/2^(12)-1/2^(12))/(1 - 1/2^(12))
    end
    return c
end

```

EDIT: error, above I don’t preserve Float32 type, so this fixes it I think:

```julia
function rand32float()
          c = -1.0f0
          while c <0.0f0 || c >= 1.0f0
            i = rand(UInt64)
            a = Float32(i >> 32)/2^(32)
            b = Float32(mod(i,2^32))/2^32
            c = (a + b/2^(12)-1.0f0/2^(12))/(1.0f0 - 1.0f0/2^(12))
           end
           return c
       end

```

Simple histograms suggest that I’m right but I didn’t write a proof.

 ![image](https://global.discourse-cdn.com/julialang/original/3X/6/c/6c2b4db8e1929b2d926250046df4b6e91989877a.png)

On my machine:

```julia
julia> @btime rand32float()
  4.969 ns (0 allocations: 0 bytes)
0.8600827395260989

julia> @btime Float32(rand(Float64))
  2.845 ns (0 allocations: 0 bytes)
0.4434461f0

```

EDIT: timing of the newer version:

```julia
julia> @btime rand32float()
  4.408 ns (0 allocations: 0 bytes)
0.06446942f0

julia> @btime Float32(rand(Float64))
  2.855 ns (0 allocations: 0 bytes)
0.5801686f0

```

---

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