Naetmul
Naetmul

Reputation: 15592

Is srand() required in 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()?

Upvotes: 5

Views: 1659

Answers (2)

RJHunter
RJHunter

Reputation: 2867

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.

Upvotes: 5

HarmonicaMuse
HarmonicaMuse

Reputation: 7893

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.

Upvotes: 4

Related Questions