(Part 4 of a series)
The ZX81 doesn’t hold simple decimals like .5 & .25 exactly. That is because (1/10) expands as (1/8)x(8/10), ie, as 2⁻³ times .8, or 125 76 204 204 204, … (where the 76 also stands for 204 as explained earlier.) Use Program 1 to display the 5-byte ZX81 representation of a number:
10 INPUT X
15 FOR J=1 TO 5
20 LET V=PEEK 16400+256*PEEK 16401
30 LET I=V+J
40 PRINT PEEK I;" ";
50 NEXT J
60 PRINT
70 GOTO 10
So .1 has no exact representation as a binary number. Its best approximation is 125 76 204 204 204 in 5 bytes. But the ZX81 doesn’t round up the quotient after division in a case like this. It holds 0.1 as 125 76 204 204 204. Hence, 0.5 is held as 127 127 255 255 255 instead of the exact result 128 0 0 0 0 and .25 is held as 126 127 255 255 255 instead of 127 0 0 0 0. (why SQR .5 and SQR .25 were affected by the old 8K ROM bug).
To hold these fractions exactly, write them as 1/2 and 1/4 (or 5/10 and 25/100). If all else fails, take a few weeks’ holiday and master machine code!
This program gives best results (exact wherever possible) for all these decimal fractions:
10 LET X=0
20 LET V=PEEK 16400+256*PEEK 16401
30 PRINT "ENTER A NUMBER THAT STARTS WITH A DECIMAL POINT AND CONTAINS NO E-FORMAT"
40 INPUT B$
50 LET B$=B$(2 TO )
60 LET L=LEN B$
70 LET D=1
80 FOR I=1 TO L
90 LET D=10*D
100 NEXT I
110 LET X=VAL B$/D
120 FOR I=V+1 TO V+5
130 IF VAL B$-D*X>=2**32/2 THEN POKE V+5,PEEK (V+5)+1
140 PRINT PEEK I;" ";
150 NEXT I
160 PRINT
170 GOTO 40
With this program, .5 now gives 128 0 0 0 0, an exact answer, .25 gives 127 0 0 0 0, an exact answer, and best 5-byte approximation. A bit surprisingly, .0000000000009094947018 gives 89 0 0 0 0, which is exactly 2⁻⁴⁰. The ZX81 is full of pleasant surprises!
Note: Type-in program listings on this website use ZMAKEBAS notation for graphics characters.