Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

random

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?

like image 903
David Kamer Avatar asked Aug 31 '18 00:08

David Kamer


People also ask

How does Julia generate random numbers?

Random number generation in Julia uses the Xoshiro256++ algorithm by default, with per- Task state. Other RNG types can be plugged in by inheriting the AbstractRNG type; they can then be used to obtain multiple streams of random numbers.

Which function is used to generate floating-point random numbers?

We can generate float random numbers by casting the return value of the rand () function to 'float'. Thus the following will generate a random number between float 0.0 and 1.0 (both inclusive).


1 Answers

Perhaps a bit more elegant, as you actually want to sample from a Uniform distribution, you can use the Distribution 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())

like image 143
Antonello Avatar answered Sep 17 '22 15:09

Antonello