Home > Enterprise >  reproduce numpy random numbers with numpy rng
reproduce numpy random numbers with numpy rng

Time:11-07

I have a script using np.random.randint that was seeded withnp.random.seed(0). Now I'd like to find how I can get the same numbers by creating a separate rng object rng = np.random.default_rng(0). Naively I would have expected these two ways to be identical, but apparently this is not the case. The reason is that I'm trying to reproduce some error from some script that used the built in method, but unfortunately now another script also influences the state of that built in RNG, which is why I'd like to decouple these.

Can anyone tell me what I have to do to get the same numbers form the rng as I do get from np.random's built in RNG?

The reason

import numpy as np
def builtin(seed=0):
    np.random.seed(seed)
    print(np.random.randint(0, 10, 5))

def default(seed=0):
    rng = np.random.default_rng(seed)
    print(rng.integers(0, 10, 5))

# unfortunately do not produce the same results:
builtin()
default()

CodePudding user response:

numpy.random.default_rng uses the new-style Generator API. This is mostly superior to the old functionality, and should be preferred in new code unless you have a specific reason not to use it, but it is not backward compatible with the old API.

The old API's way of creating a new RNG object is numpy.random.RandomState:

rng = np.random.RandomState(0)
print(rng.randint(0, 10, 5))
  • Related