5

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

  • this doesn't ever return 1 since rand's range is [0, 1)
  • this skips out on a lot of values: let's say eps() == 0.1 for argument's sake, then rand returns from (0.1, 0.2, 0.3, ..., 0.9), and after this computation you get results from (-0.8, -0.6, -0.4, ..., 0.8), so the result is not uniformly random in the range anymore.

(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?

Sundar R
  • 13,776
  • 6
  • 49
  • 76

1 Answers1

9

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.

niczky12
  • 4,953
  • 1
  • 24
  • 34
hdavid16
  • 126
  • 3
  • Thanks! I did not know about this option, this seems ideal. The performance is great too, faster than either of the methods in the question. – Sundar R Aug 18 '21 at 05:53
  • Maybe mention that `rand(Uniform(-1,1))` generates a random scalar? I very often see people doing `rand(distr, 1)[1]` when they want a scalar. – DNF Aug 18 '21 at 10:42