# Obtain the current value of the seed used by the random number generator

I would like to be able to do something like the following pseudocode:

SeedRandom[someNumber];  (* Initialize the random number generator's seed for reproducible results *)

Do
Run a batch of Monte Carlo simulations;
Obtain the current value of the seed of Mathematica's RNG;
DumpSave["filename.mx",{monteCarloResults,currentSeedValue}];
Until N batches have run


The idea here is that if something goes wrong (Mathematica kernel crashes, etc.), having saved both the results of the simulation and the current seed value of the random number generator's, I wouldn't have to start over and the results would still be fully deterministic/reproducible. I'd just load the seed value from the last file saved, call SeedRandom[currentSeedValue], initialize the loop counter to the value for the next iteration, and go on my merry way.

Does Mathematica have a function that returns the current value of the seed?

You may get the current state of the random generator with

gs = RandomGetRandomState[];


This can be loaded back into the generator later with

RandomSetRandomState@gs;


Then you can continue from where you left off.

Note that these are undocumented functions and as such there is no guarantee that the functionality will remain the same in future versions of Wolfram Language.

Hope this helps.

• Perfect! Exactly what I was looking for – Matt Jan 4 '19 at 15:05
• It might also suffice to save and restore the value of $RandomState. – Daniel Lichtblau Jan 4 '19 at 16:11 • @Daniel, $RandomState will only affect the old Random[type, range] method, but not the newer RandomReal[]/RandomInteger[] functions. – J. M.'s technical difficulties Jan 5 '19 at 4:46
• @J.M.iscomputer-less: Oof. How did I not know that? Chagrined am I. – Daniel Lichtblau Jan 5 '19 at 16:03

This is too long for a comment on Edmund's post, so I shall write here a demonstration of this undocumented functionality:

# First session

In:= SeedRandom[2019, Method -> "ExtendedCA"];

In:= RandomInteger[{-9, 9}, 30]
Out:= {4, -2, 8, 7, -1, 5, -3, -8, 6, -7, -4, 1, 4, 7, -9, -7, 2, -1, -8, -6, 6, -7, 1, 7, 0, 9,
-1, 4, 7, 9}

In:= Put[RandomGetRandomState[], FileNameJoin[{$TemporaryDirectory, "randstate.m"}]] In:= RandomInteger[{-9, 9}, 10] Out:= {-5, 7, -7, -2, -2, 6, 1, -8, -4, -4} In:= Exit[]  # Second session In:= RandomSetRandomState[Get[FileNameJoin[{$TemporaryDirectory, "randstate.m"}]]]

In:= RandomInteger[{-9, 9}, 10]
Out:= {-5, 7, -7, -2, -2, 6, 1, -8, -4, -4}


Note that the output of RandomInteger[{-9, 9}, 10] in both sessions is the same.