Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a random integer in range in Julia

Tags:

random

julia

I am migrating from MATLAB to Julia and I am trying to generate a random integer in range 1:n.

For n < 21,

rand(r[1:n]) works.

However for n > 20, for example, rand(r[1:21]), I get this message:

ERROR: BoundsError() in getindex at range.jl:121 
like image 715
user3411759 Avatar asked Jun 20 '14 12:06

user3411759


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.

How do you set the random seed in Julia?

In Julia, you can set a seed to the random number generator using the srand() function. The code example below sets the seed to 1234. Generating a random variable with rand(1) after setting the seed to 1234 will always generate the same number, i.e. it will always return 0.5908446386657102.

How do you insert a random value in a table?

To create a random integer number between two values (range), you can use the following formula: SELECT FLOOR(RAND()*(b-a+1))+a; Where a is the smallest number and b is the largest number that you want to generate a random number for.


1 Answers

You can give a range as the first argument to rand, as in rand(1:n):

julia> rand(1:10) 7  julia> rand(1:10,10,10) 10x10 Array{Int64,2}:  10   2  5  8   5   5  3   7   1   3   5   1  4  2   4   4  1   6   6   9   8   1  3  9   4   8  7   8   7  10   3   8  1  5   7   9  7   8  10   7   5   8  5  6   6   2  2   7   4   3  10   4  8  8  10   5  1  10   5   1   6   1  8  1   6   5  7  10   6  10   5  10  2  5   4   5  4   1   3   9   5   4  6  4   4   1  7   8   1   5  10   2  6  4   3  10  7   3   8   7 

The first argument to the general rand function usually gives a "thing to sample from", be it a range of values or a distribution object as defined in Distributions.jl.

like image 115
StefanKarpinski Avatar answered Sep 24 '22 07:09

StefanKarpinski