PY-94

Replay a Sequence of Random Draws

  • Medium
  • Random Replay
  • Python

Task

Write replay_random_draws(rng, requests, expected_draws=None).

rng is one already-created NumPy Generator. requests is a non-empty list of records. Every record must contain exactly these keys:

kind, low, high, size

kind is either "uniform" or "integers". size is a non-empty tuple or list of positive integers. A uniform request uses finite numeric bounds with low < high and produces float64 values from [low, high). An integer request uses integer bounds with low < high and produces int64 values from [low, high). Requests are executed in their supplied order. The same generator advances from one request to the next.

expected_draws is optional. When it is omitted, the function records the actual run and sets first_divergence to None. When it is supplied, it must contain one array for each request. Compare each actual array with its expected array exactly. If every array agrees, first_divergence is None. Otherwise, report the first request that differs:

  • If the shapes differ, return a record with call_index, index=None, expected_shape, and observed_shape.
  • If the shapes agree, return call_index, the first differing zero-based index, and the scalar expected and observed values at that index.

Return a new dictionary with exactly these keys:

draws, calls, first_divergence, generator

draws is a tuple of new arrays. calls is a tuple of normalized request records, with each size stored as a tuple. generator is the bit-generator class name. Do not modify requests or expected_draws, create another generator, reseed the supplied generator, or compare with a tolerance. A valid call advances rng once for every request, even when an expected run is being checked. Invalid requests or an incorrectly shaped expected run must raise ValueError before any draw is made.

The function does not promise that a seed alone is portable across all NumPy versions. The generator algorithm, starting state, ordered requests, and environment together form the replay contract.

Example

To diagnose a changed protocol, keep the same starting seed and change one request. Passing the reference draws identifies the first changed call rather than only reporting that the final sequence differs.

Your implementation

You may import NumPy as np. Do not print, ask for input, or create a hidden generator.