0

Let's assume that I want to use the function sample() within the random module in python on input [1,2,3,4] and obtain [2,3,1,4].

My objective is now rolling back this operation to obtain the previous state, meaning that I want to again apply the sample() (or any other function) on [2,3,1,4] so that the result is back to [1,2,3,4].

This is kind of I need an unsample() instruction.

Can I do it by the use of setstate() and getstate??

  • *Can I do it by the use of setstate() and getstate??* Try it and see. Don't be afraid to experiment. – President James K. Polk Oct 24 '22 at 17:33
  • note that moving the state to another machine might cause some of the "real-valued" distributions to return sightly different values. e.g. uniform will probably be OK, but normal/Gaussian distribution might not. e.g. https://stackoverflow.com/q/72817047/1358308 (which was noticed via Numpy, but I'd expect the same artifact via the `random` module) – Sam Mason Oct 24 '22 at 19:36

1 Answers1

0

If all you want is to get back to the original input of [1,2,3,4], it's easy. Just don't clobber the original with your sample. Put the results of sampling into a different variable:

import random

my_data = [1,2,3,4]
print(f"original before sampling: {my_data}")

sampled_data = random.sample(my_data, 4)
print(f"after sampling, original: {my_data}, sample: {sampled_data}")

produces, for example:

original before sampling: [1, 2, 3, 4]
after sampling, original: [1, 2, 3, 4], sample: [2, 1, 3, 4]

If you want a do-over to reproduce the same sample, then you should use gestate()/setstate() to reset the pseudo-random number generator's internal state in addition to preserving the original input:

import random

my_data = [1,2,3,4]
print(f"original before sampling: {my_data}")

rng_state = random.getstate()
sampled_data = random.sample(my_data, 4)
print(f"after sampling, original: {my_data}, sample: {sampled_data}")

sampled_data = random.sample(my_data, 4)
print(f"without resetting PRNG, original: {my_data}, sample: {sampled_data}")

random.setstate(rng_state)
sampled_data = random.sample(my_data, 4)
print(f"after resetting PRNG, original: {my_data}, sample: {sampled_data}")

produces, for example:

original before sampling: [1, 2, 3, 4]
after sampling, original: [1, 2, 3, 4], sample: [2, 1, 3, 4]
without resetting PRNG, original: [1, 2, 3, 4], sample: [3, 4, 1, 2]
after resetting PRNG, original: [1, 2, 3, 4], sample: [2, 1, 3, 4]
pjs
  • 18,696
  • 4
  • 27
  • 56