Re: [julia-dev] How to generating random numbers between -1 and 1 inclusive

1,938 views
Skip to first unread message

Harlan Harris

unread,
Jul 22, 2012, 10:29:48 AM7/22/12
to juli...@googlegroups.com
rand()*2-1

or, if you want to generate a bunch of them with different intervals:

unifrnd(from,to) = rand()*(to-from) + from

or, vectorized:

unifrnd(n, from, to) = rand(n) .* (to-from) .+ from

 -Harlan

On Sun, Jul 22, 2012 at 5:11 AM, aps12 <ajaysi...@gmail.com> wrote:

Hello ,

First let me thank you for the Julia language.

In octave I could do unifrnd(-1 , 1) to generate random number between -1 and 1 .

Is there a way to do the same in Julia , or something that emulate like the above.

Thanks

--
 
 
 

John Myles White

unread,
Jul 22, 2012, 12:10:52 PM7/22/12
to juli...@googlegroups.com
In principle, I would suggest this, which is going to be the correct way to do this in Julia in the future:

load("distributions.jl")
rand(Uniform(-1, 1))

Unfortunately there is currently a bug in it that I won't have time to fix today. If someone else is motivated to learn how Julia's RNG's work, you can look in extras/distributions.jl. You can also confirm that the generator is not working as I expect it should based on this loop:

for i = 1:100
println(rand(Uniform(-1, 1)))
end

On my machine that produces 100 negative numbers, an event with probability 2^-100 if the generator worked.

-- John

Douglas Bates

unread,
Jul 22, 2012, 12:49:16 PM7/22/12
to juli...@googlegroups.com
On Sunday, July 22, 2012 11:10:52 AM UTC-5, John Myles White wrote:
In principle, I would suggest this, which is going to be the correct way to do this in Julia in the future:

load("distributions.jl")
rand(Uniform(-1, 1))

Unfortunately there is currently a bug in it that I won't have time to fix today. If someone else is motivated to learn how Julia's RNG's work, you can look in extras/distributions.jl. You can also confirm that the generator is not working as I expect it should based on this loop:

for i = 1:100
  println(rand(Uniform(-1, 1)))
end

On my machine that produces 100 negative numbers, an event with probability 2^-100 if the generator worked.

A thinko on my part.  Now fixed. 

Douglas Bates

unread,
Jul 22, 2012, 12:55:34 PM7/22/12
to juli...@googlegroups.com
By the way, a slightly cleaner call is

println(rand(Uniform(-1,1), (100,)))
Reply all
Reply to author
Forward
0 new messages