Search code examples
randomjulia

How can I generate a range of random floating point numbers in Julia?


I noticed that rand(x) where x is an integer gives me an array of random floating points. I want to know how I can generate an array of random float type variables within a certain range. I tried using a range as follows:

rand(.4:.6, 5, 5)

And I get:

 0.4  0.4  0.4  0.4  0.4
 0.4  0.4  0.4  0.4  0.4
 0.4  0.4  0.4  0.4  0.4
 0.4  0.4  0.4  0.4  0.4
 0.4  0.4  0.4  0.4  0.4

How can I get a range instead of the lowest number in the range?


Solution

  • Perhaps a bit more elegant, as you actually want to sample from a Uniform distribution, you can use the Distributions package:

    julia> using Distributions
    julia> rand(Uniform(0.4,0.6),5,5)
    5×5 Array{Float64,2}:
     0.547602  0.513855  0.414453  0.511282  0.550517
     0.575946  0.520085  0.564056  0.478139  0.48139
     0.409698  0.596125  0.477438  0.53572   0.445147
     0.567152  0.585673  0.53824   0.597792  0.594287
     0.549916  0.56659   0.502528  0.550121  0.554276
    

    The same method then applies from sampling from other well-known or user-defined distributions (just give the distribution as the first parameter to rand())