(Lispex)sicp.io
3.6 · Pseudorandom state

A seed makes changing output reproducible.

A generator can keep one private seed, replace it on every call, and still reproduce the same sequence when it starts from the same value.

Guiding question

How can a stateful generator change every call yet repeat exactly?

  • Treat the current seed as one private mutable location
  • Follow a recurrence from one generated value to the next
  • Distinguish deterministic pseudorandomness from external randomness
  • Reproduce a sequence by constructing a generator with the same seed

make-rand closes over seed. Each call multiplies the current value by 48271, takes the remainder modulo 2147483647, stores that result back in seed, and returns it. The next call therefore starts from the value produced by the previous call.

The recurrence is deterministic. Two separately constructed generators begin with private locations, but equal starting seeds make their value sequences equal. This small generator is useful for studying state and reproducibility, not for cryptography or security decisions.

Lispex · SICP sourceScheme-compatible SICP syntax executed by the Lispex SICP profile.
(begin
  (define (make-rand seed)
    (lambda ()
      (set! seed (remainder (* seed 48271) 2147483647))
      seed))
  (define rand (make-rand 1))
  (list (rand) (rand) (rand) (rand) (rand)))
Lispex learning runtimeLispex SICP profile 1.0.0
Loading Lispex SICP runtime
Lispex · SICP source192 / 1,048,576 UTF-8 bytes
Examples
Result
Output
Value
Diagnostic
Visible execution0 / 0 trace events
    This browser result is not a Lispex Vouch record or authority.wasm —
    Expected observation

    The first program returns (48271 182605794 1291394886 1914720637 2078669041). The second returns (337897 1278240558 337897 1278240558).

    Trace focus

    Find each set! of the captured seed and follow the stored result into the next call. In the second program, separate the two closure environments even though their first and second values match.

    Try it yourself

    Change the program before you read the hint.

    Change only the right generator seed from 7 to 8. Predict which positions can still match before running the program.

    Show one hint

    The two generators have independent locations. Equal recurrences reproduce a sequence only when their starting seeds are equal.