7

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?

Matt
  • 453
  • 2
  • 13

2 Answers2

11

You may get the current state of the random generator with

gs = Random`GetRandomState[];

This can be loaded back into the generator later with

Random`SetRandomState@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.

Edmund
  • 42,267
  • 3
  • 51
  • 143
1

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[1]:= SeedRandom[2019, Method -> "ExtendedCA"];

In[2]:= RandomInteger[{-9, 9}, 30]
Out[2]:= {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[3]:= Put[Random`GetRandomState[], FileNameJoin[{$TemporaryDirectory, "randstate.m"}]]

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

In[5]:= Exit[]

Second session

In[1]:= Random`SetRandomState[Get[FileNameJoin[{$TemporaryDirectory, "randstate.m"}]]]

In[2]:= RandomInteger[{-9, 9}, 10]
Out[2]:= {-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.

J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574