Random Numbers on the Atari: RANDOM, RND, Dice and Shuffles

Atari text screen showing a histogram of 360 rolls of two dice, with the bar for 7 the longest and the bars for 2 and 12 the shortest

Games need dice, shuffled cards, wandering monsters and stars in random places. Most home computers of the early 1980s produced "random" numbers with a formula in ROM. The Atari has a hardware source instead: POKEY, the chip that also makes the sound and reads the keyboard, contains a noise generator that runs non-stop and can be read like a memory location. This guide shows how that generator works, how BASIC's RND function is built on it, and how to turn either into fair dice rolls, ranges and shuffles.

What you'll learn: what PEEK(53770) really returns, how Atari BASIC's RND is computed, how to get unbiased integers in any range, a Fisher–Yates card shuffle, a fair die in machine language, and how to get a repeatable sequence when you need one.

What you need: any Atari 8-bit computer or emulator with Atari BASIC. The machine-language routine is optional; its bytes are given as DATA statements.

1. Two ways to ask for a random number

Atari BASIC gives you two sources:

Source What you get Typical use
RND(0) A fraction from 0 up to (but never reaching) 1 Formulas such as INT(N*RND(0))
PEEK(53770) A whole number from 0 to 255 Bytes, colours, quick coin flips

Location 53770 ($D20A) is POKEY's RANDOM register. It is a read-only hardware register: writing to the same address does something unrelated (it resets serial-port status bits), so never POKE it. Try both in direct mode:

FOR N=1 TO 10:PRINT PEEK(53770),RND(0):NEXT N

The argument to RND is ignored. RND(0), RND(1) and RND(99) all behave the same, and there is no way to "seed" it.

2. How RANDOM works

POKEY contains three polynomial counters, also called linear feedback shift registers. Each one shifts a row of bits along and feeds back a new bit made by XORing two of the old ones. The result looks like noise but is completely determined by the starting state. The 4-bit and 5-bit counters are used only for sound. The third is 17 bits long (polynomial 1+x¹²+x¹⁷) and gives the hiss of distortion 8 and the explosions in countless games. RANDOM lets the CPU see the top eight bits of that 17-bit register.

Two details matter in practice:

  • It never stops. The register shifts one bit for every machine cycle, about 1.79 million times a second, whether or not anyone reads it. A 17-bit counter repeats after 2¹⁷−1 = 131,071 steps, which is only about 0.07 seconds. The numbers seem random to a BASIC program because the time between two reads is irregular and much longer than that.
  • It can be shortened. Setting bit 7 of AUDCTL (53768, $D208) switches the generator to a 9-bit counter (1+x⁴+x⁹) with a period of only 511 steps. That changes the sound of noise channels and it changes what RANDOM returns too. The Advanced POKEY guide covers the audio side.

The register only runs while POKEY is out of its initialization mode. If both of the low two bits of SKCTL (53775, $D20F) are cleared, the counter is frozen and RANDOM reads 255 until normal operation resumes.

3. How Atari BASIC builds RND

The interpreter's RND routine is short. It reads RANDOM twice to make a 16-bit integer from 0 to 65535, converts that to floating point and divides it by 65536. Two consequences follow:

  • RND(0) can return only 65,536 different values. That is plenty for dice and screen positions, but INT(100000*RND(0)) can never produce most of the numbers from 0 to 99999.
  • Every call performs a floating-point division, and Atari BASIC's maths routines are slow. If a byte is all you need, PEEK(53770) skips the arithmetic.

Replacement interpreters may differ. Altirra BASIC, the free Atari BASIC-compatible ROM built into Altirra and atari800, prints ten-digit RND values, so do not rely on the exact format of RND output.

4. Integers in a range

The classic formula for a whole number from L to H is:

X=INT((H-L+1)*RND(0))+L

For example, INT(6*RND(0))+1 rolls a die and INT(40*RND(0)) gives a screen column from 0 to 39. With RANDOM, scale the byte down:

X=INT(PEEK(53770)*N/256)

This gives 0 to N−1. Because 256 values do not divide evenly into most ranges, a few results come up slightly more often: with N=6, four of the six faces get 43 of the 256 byte values and two get 42. That is under half a percent, which is fine for a monster's path but not for a gambling game.

When the range divides 256 evenly, the result is exact. INT(PEEK(53770)/16) is a fair 0–15 and PEEK(53770)>127 is a fair coin (true is 1, false is 0). For other ranges, reject the values that cause the bias and read again. 252 is the largest multiple of 6 below 256, so throw away 252–255:

200 R=PEEK(53770):IF R>251 THEN 200
210 D=R-INT(R/6)*6+1:RETURN

Atari BASIC has no MOD operator, so R-INT(R/6)*6 does the job. On average this subroutine needs only 1.02 reads per roll.

5. Dice: seeing the distribution

This program rolls two dice 360 times with that subroutine and draws a bar for each total. In GRAPHICS 0, COLOR 160 makes PLOT and DRAWTO draw inverse spaces, which gives solid bars without any special characters in the listing.

10 DIM C(12):GRAPHICS 0:POKE 752,1
20 FOR T=2 TO 12:C(T)=0:NEXT T
30 PRINT "ROLLING TWO DICE 360 TIMES"
40 FOR I=1 TO 360
50 GOSUB 200:S=D:GOSUB 200:S=S+D
60 C(S)=C(S)+1:NEXT I
70 COLOR 160
80 FOR T=2 TO 12:Y=T+1
90 POSITION 2,Y:PRINT T;:POSITION 33,Y:PRINT C(T);
100 W=INT(C(T)/2):IF W>0 THEN PLOT 6,Y:DRAWTO 5+W,Y
110 NEXT T
120 POSITION 2,16:PRINT "EXPECTED: 10 20 30 40 50 60 50 ...":END
200 R=PEEK(53770):IF R>251 THEN 200
210 D=R-INT(R/6)*6+1:RETURN

POKE 752,1 hides the cursor. With 36 equally likely combinations, 360 rolls should give about 10 twos, 60 sevens and 10 twelves. Every run differs, but the triangle shape always appears. A common beginner's mistake is INT(11*RND(0))+2 for "two dice": that makes 2 as likely as 7. Roll each die separately and add them.

6. Shuffling a deck

To deal cards without repeats, shuffle the whole deck once and then deal from the top. The Fisher–Yates shuffle walks down the deck from the last card. It swaps each card with a randomly chosen card at or before that position, so every ordering is equally likely. Atari BASIC has no string arrays, but the deck fits in one string with one character per card (codes 1–52), which is compact and fast to swap:

60 DIM D$(52),T$(1)
70 FOR I=1 TO 52:D$(I)=CHR$(I):NEXT I
80 FOR I=52 TO 2 STEP -1
90 J=INT(RND(0)*I)+1
100 T$=D$(I,I):D$(I,I)=D$(J,J):D$(J,J)=T$
110 NEXT I
120 FOR I=1 TO 13:PRINT ASC(D$(I));" ";:NEXT I:PRINT

Line 120 deals a 13-card hand. To decode a card number C, the suit is INT((C-1)/13) and the rank is C-13*INT((C-1)/13). Avoid the tempting shortcut of picking random cards and retrying when you hit one already dealt: it slows down badly near the end of the deck.

The same loop shuffles a numeric array. Use T=A(I):A(I)=A(J):A(J)=T for the swap.

7. Random numbers in machine language

In assembly, RANDOM is a single instruction: LDA $D20A. Use AND to cut the byte down to a power-of-two range, then reject out-of-range values just as in BASIC. This routine is called from BASIC with X=USR(1536) and returns a fair 1–6. It was assembled with MADS:

; USR routine: X=USR(1536) returns a fair die roll, 1-6
RANDOM  = $D20A
FR0     = $D4
        org $0600
        pla             ; discard argument count
roll    lda RANDOM
        and #7          ; 0-7
        cmp #6
        bcs roll        ; reject 6 and 7, try again
        adc #1          ; carry is clear here: 1-6
        sta FR0
        lda #0
        sta FR0+1
        rts

BASIC loader and test:

10 FOR I=0 TO 18:READ B:POKE 1536+I,B:NEXT I
20 DATA 104,173,10,210,41,7,201,6,176,247
30 DATA 105,1,133,212,169,0,133,213,96
40 DIM C(6):FOR I=1 TO 600:D=USR(1536):C(D)=C(D)+1:NEXT I
50 FOR I=1 TO 6:PRINT I;": ";C(I):NEXT I

The PLA removes the argument count that USR pushes, and the result goes in FR0 ($D4–$D5), where BASIC picks it up as the function's value. See Calling Machine Language from Atari BASIC with USR for the details.

One trap is specific to machine code. Because RANDOM shifts one bit per cycle, two reads a few cycles apart overlap: most of the bits in the second value are the first value's bits, moved along. When you need two independent bytes in a row, put some work between the reads, or use one byte for two purposes (the low nibble for X, the high nibble for Y). Reading RANDOM at a fixed point in a tightly timed loop is also risky. With the 9-bit mode selected and one read per scan line, the values settle into a short repeating pattern.

8. When you want the same "random" numbers twice

RANDOM cannot be seeded. That is a problem for a level generator that should rebuild the same maze from a level number, or for testing a program against the same sequence of events. For those jobs, use a small software generator whose state you control. The Lehmer generator below multiplies by 75 and takes the remainder modulo the prime 65537. It visits all 65,536 values from 1 to 65536 before repeating, and its intermediate results stay below five million, so Atari BASIC's nine-digit floating point keeps them exact:

130 S=1234:FOR I=1 TO 5:GOSUB 300:PRINT S;" ";:NEXT I:PRINT
140 S=1234:FOR I=1 TO 5:GOSUB 300:PRINT S;" ";:NEXT I:PRINT
150 END
300 S=S*75:S=S-INT(S/65537)*65537:RETURN

Both lines print 27013 59865 33359 11519 11944. Set S to any value from 1 to 65536 and you get a sequence that repeats exactly. Scale it as before, for example INT(S*6/65537)+1. A good trick is to seed it from the hardware at the start of a game, with S=PEEK(53770)*256+PEEK(53770)+1. Also store that seed, so a player can replay the same game.

Troubleshooting

  • PEEK(53770) always returns 255. POKEY is in initialization mode, which happens if something has written 0 to SKCTL (53775). POKE 53775,3 restores normal operation, and so does any SOUND statement.
  • Random numbers look patterned after a sound routine. AUDCTL bit 7 is set and the generator is in 9-bit mode. POKE 53768,0 or any SOUND statement (which resets AUDCTL) returns it to 17 bits.
  • A game starts identically every time in an emulator. An emulator can boot with exactly the same timing on every run, so a program that reads RANDOM at a fixed moment after power-on sees the same value each time. Altirra has a randomization setting among its boot options. In your own code, take the seed when the player presses a key: human timing is never the same twice.
  • ERROR 9 in a dice or shuffle program. An index went out of range. INT(6*RND(0)) gives 0–5, not 1–6; add 1 before using it as a subscript, or DIM the array one larger.
  • The "random" number is always even, or always below 128. Check the scaling. INT(PEEK(53770)/2)*2 and similar slips are easy to make. Print 20 values in direct mode before trusting a formula.

Further reading

  • Mapping the Atari by Ian Chadwick (revised edition, COMPUTE! Books, 1985): locations 53768 (AUDCTL) and 53770 (RANDOM).
  • The Atari BASIC Source Book by Bill Wilkinson, Kathleen O'Brien and Paul Laughton (COMPUTE! Books, 1983): the complete source for Atari BASIC, including the RND routine.
  • De Re Atari (Atari, Inc., 1982), Chapter 7: POKEY's polynomial counters and noise.
  • Altirra Hardware Reference Manual by Avery Lee: the POKEY chapter and the appendix on polynomial counters, down to the exact bit sequences.
  • On this site: POKEY Sound Basics, Advanced POKEY, Atari BASIC String Handling and Tricks and Calling Machine Language from Atari BASIC with USR.

Credits