Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is srand() required in Julia?

Tags:

random

julia

Some low-level languages like C require the programmer to set seed (usually srand(time(0)) if the user wants a different sequence of random numbers whenever the program runs. If it is not set, the program generates the same sequence of random numbers for each run.

Some high-level languages automatically set the seed if it is not set at first.

In Julia, if I want to generate a new sequence of random numbers each time, should I call srand()?

like image 681
Naetmul Avatar asked Feb 26 '18 05:02

Naetmul


2 Answers

If you call Julia's srand() without providing a seed, Julia will use system entropy for seeding (essentially using a random seed).

On startup (specifically during initialisation of the Random module), Julia calls srand() without arguments. This means the global RNG is initialised randomly.

That means there's usually no need to call srand() in your own code unless you want to make the point that your random results are not meant to be reproducible.

like image 139
RJHunter Avatar answered Sep 30 '22 20:09

RJHunter


Julia seeds the random number generator automatically, you use srand with a known seed, in order to recreate the same pseudo random sequence deterministically (useful for testing for example), but if you want to generate a different random sequence each time, all you need is to call rand.

help?> srand
search: srand sprand sprandn isreadonly StepRange StepRangeLen ClusterManager AbstractRNG AbstractUnitRange CartesianRange

  srand([rng=GLOBAL_RNG], seed) -> rng
  srand([rng=GLOBAL_RNG]) -> rng

  Reseed the random number generator: rng will give a reproducible sequence
  of numbers if and only if a seed is provided. Some RNGs
  don't accept a seed, like RandomDevice. After the call to srand, rng is 
  equivalent to a newly created object initialized with the
  same seed.
like image 44
HarmonicaMuse Avatar answered Sep 30 '22 20:09

HarmonicaMuse