39

I would like to do a couple of checkings using the random generator for normal distributed numbers in julia. So what I would like is to obtain the same sequence of pseudo-random numbers.

Actually, I do random matrices, so I would like that both of my programs generate:

A = randn(dim,dim)                                                                                                                                                                           
H = (A + A')/sqrt(2)

the same H-matrix

3 Answers 3

45

Updated answer, for Julia 0.7 onwards.

import Random
Random.seed!(1234)
dim = 5
A = randn(dim,dim)
H = (A + A')/sqrt(2)

Previous answer, for Julia 0.6 and earlier.

You are looking for the srand function, e.g.

srand(1234)
dim = 5
A = randn(dim,dim)
H = (A + A')/sqrt(2)

Will always produce the same results.

7
  • which is the range of the argument of srand? Aug 7, 2014 at 22:52
  • There actually multiple versions of srand, try methods(srand) and ?srand for more info. Aug 9, 2014 at 8:27
  • The srand documentation link is dead.
    – a06e
    Jan 30, 2017 at 17:53
  • @becko not anymore! :)
    – ahogen
    Oct 30, 2017 at 21:42
  • 2
    srand does not exist in Julia 0.7/1.0
    – crlb
    Oct 18, 2018 at 7:12
11

In Julia 0.7/1.0, you can use Random.seed!(1234); https://docs.julialang.org/en/v1/stdlib/Random/index.html#Generators-(creation-and-seeding)-1

1
  • 2
    I think it is the only function you can use now.
    – crlb
    Oct 18, 2018 at 7:13
1

I think Random.seed!(int) applies only on the next random for some reason. you need to reuse it every time you call. You can set the random seed as a function though like

function rr()
    rng = MersenneTwister(22);
    return rng
end

and then call in inside the rand() function like

rand(rr(), 1)

Example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.