38

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

user2820579
  • 3,261
  • 7
  • 30
  • 45

3 Answers3

44

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.

IainDunning
  • 11,546
  • 28
  • 43
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

Rob Donnelly
  • 2,256
  • 2
  • 20
  • 29
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

Orfeas Bourchas
  • 353
  • 1
  • 6