Sundar R
Sundar R

Reputation: 14695

Getting a random float value in [-1, 1] in Julia

Is

p = rand(-1.:eps():1., 100000)

a good way to get random Float values in [-1, 1]?

A common suggestion seems to be 2. * rand(100000) - 1. instead, but

(Note: Performance-wise, my version at the top seems to be 4x slower than the latter one. )

What is the generally recommended way of getting a uniformly random floating point number in a given range?

Upvotes: 5

Views: 2004

Answers (1)

hdavid16
hdavid16

Reputation: 126

Use the Distributions.jl package to create a Uniform distribution between (-1, 1) and sample from it using rand.

julia> using Distributions

julia> rand(Uniform(-1, 1), 10000)
10000-element Vector{Float64}:
  0.2497721424626267
  ...
 -0.27818099962886844

If you don't need a vector but just a single scalar number, you can call it like this (thanks to @DNF for pointing this out):

julia> rand(Uniform(-1,1))
-0.02748614119728021

You can also sample different shaped matrices/vectors too:

julia> rand(Uniform(-1, 1), 3, 3)
3×3 Matrix{Float64}:
 -0.290787  -0.521785    0.255328
  0.621928  -0.775802   -0.0569048
  0.987687   0.0298955  -0.100009

Check out the docs for Distributions.jl here.

Upvotes: 9

Related Questions