sicp.io
3.1.3 · 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 lesson generator makes state and reproducibility directly observable.

SICP code192 of 1,048,576 UTF-8 bytes
Examples
Result
Output
Value
Diagnostic
Execution trace0 / 0 events
    Programs run in the browser with their result and execution trace.
    Expected result

    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 and compare the result.

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

    Show hint

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

    Complete this lesson

    0 of 21 lessons complete in this chapter0%