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 *)

    Run a batch of Monte Carlo simulations;
    Obtain the current value of the seed of Mathematica's RNG;
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 = Random`GetRandomState[];

This can be loaded back into the generator later with


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.

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


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.