82309

python random.getstate() and random.setstate()

Question:

Learning the module random here, in the very beginning there are book-keeping functions, I understand that to set a specific seed is to make sure obtaining same random number.

but, what about the getstate() and setsate()? <a href="https://docs.python.org/3/library/random.html#bookkeeping-functions" rel="nofollow">link</a> In the documentation, it has no introduction for what this state means, and if I don't know what it means, how could I set it right?

<blockquote>

<strong><em>random.getstate()</em></strong>

Return an object capturing the current internal state of the generator. This object can be passed to setstate() to restore the state.

<strong><em>random.setstate(state)</em></strong>

state should have been obtained from a previous call to getstate(), and setstate() restores the internal state of the generator to what it was at the time getstate() was called.

</blockquote>

Thanks,

Answer1:

Why not try it out?

import random random.seed(42) print(random.sample(range(20),k=10)) st = random.getstate() # remeber this state print(random.sample(range(20),k=20)) # print 20 random.setstate(st) # restore state print(random.sample(range(20),k=10)) #print same first 10

Output:

[12, 0, 4, 3, 11, 10, 19, 1, 5, 18] [4, 9, 0, 3, 10, 8, 16, 7, 18, 17, 14, 6, 2, 1, 5, 11, 15, 13, 19, 12] [4, 9, 0, 3, 10, 8, 16, 7, 18, 17]

Obvoiusly, you can go back and reproduce the same values over and over if you get a state and restore it.

You can not use different randoms in between though or you alter the state.

random.setstate(st) # go back again print(random.sample(range(99),k=2)) # do something different print(random.sample(range(20),k=18))

Output:

[21, 50] # something different after setting state [0, 3, 11, 9, 18, 8, 17, 19, 16, 7, 15, 1, 10, 2, 12, 5, 13, 14] # changed values <hr />import random import timeit t1 = timeit.timeit(stmt = """random.seed(42) random.randint(1,10)""",number=10000,setup="import random") t2 = timeit.timeit(stmt = """ random.randint(1,10) random.setstate(s)""",number=10000,setup="""import random s = random.getstate()""") print(t1,t2)

Output:

# seed() time setstate() time 0.5621587821914207 0.49502014443357545

Answer2:

Python's default generator is a <a href="https://en.wikipedia.org/wiki/Mersenne_Twister" rel="nofollow">Mersenne Twister</a> with a state space that is 19937 bits, much larger than what you think of as the seed.

You can think of it conceptually as three functions:

<ul><li>f(seed) -> state<sub>0</sub></li> <li>g(state<sub>i</sub>) -> state<sub>i+1</sub></li> <li>h(state<sub>i</sub>) -> outcome<sub>i</sub></li> </ul>

When you start with a seed value using random.seed(), it generates a full state value of 19937 bits <strong>one time</strong> using function f(). Each time you use the generator, it advances to the next 19937 bit state using g() and returns the output found by collapsing the updated state down a single integer using h().

Normally you don't actually see the internal state which is at the core of the generator. getstate() bypasses the collapsing function h(), and setstate() bypasses the seeding function f(), so that you can reproduce your sequence from any point without having to go all the way back to the beginning and reproduce the entire sequence to that point.

Most people don't need to (and shouldn't) use the get/setstate capability, but it can be useful for pulling some clever mathematical tricks to <a href="https://en.wikipedia.org/wiki/Variance_reduction" rel="nofollow">reduce variability of Monte Carlo estimators</a>.

Recommend

  • What are common sources of randomness in Machine Learning projects with Keras?
  • Service fabric rollback to previous version from visual stuido or service fabric explorer
  • Cannot read property setState of undefined in axios callback
  • Is there a common practice to track the user session across browser window?
  • Passing Props from State to Child
  • How to add new index numbers to the upsampled data while preserving the orginal indices one
  • Symfony2.1 form date field: Argument 1 passed to … must be an instance of DateTime
  • Recursion Control flow
  • C++ Pointer Arrays
  • BackgroundTransferRequest WP7
  • Deduce parent class of inherited method in C++
  • Processing different annotations with the same Processor instance
  • crash in __tcf_0
  • Open Existing DB in MySQL WorkBench
  • C#: Import/Export Settings into/from a File
  • Passing “get” parameters doesn't work, parameter not visible in the link
  • Reading a file into a multidimensional array
  • How to assign byte[] as a pointer in C#
  • Android application: how to use the camera and grab the image bytes?
  • Calling Worksheet functions from vba in foreign language versions of Excel
  • Do I need to reset a Perl hash index?
  • Google Custom Search with transparent background
  • How to clear text inside text field when radio button is select
  • Can I check if a recipient has an automatic reply before I send an email?
  • Scrapy recursive link crawler
  • How to recover from a Spring Social ExpiredAuthorizationException
  • Does CUDA 5 support STL or THRUST inside the device code?
  • javascript inside java/jsp code
  • Why winpcap requires both .lib and .dll to run?
  • align graphs with different xlab
  • Return words with double consecutive letters
  • Python: how to group similar lists together in a list of lists?
  • How to set the response of a form post action to a iframe source?
  • Can Visual Studio XAML designer handle font family names with spaces as a resource?
  • How can I remove ASP.NET Designer.cs files?
  • Are Kotlin's Float, Int etc optimised to built-in types in the JVM? [duplicate]
  • unknown Exception android
  • Busy indicator not showing up in wpf window [duplicate]
  • Reading document lines to the user (python)
  • Python/Django TangoWithDjango Models and Databases