Classic Computer Magazine Archive COMPUTE! ISSUE 34 / MARCH 1983 / PAGE 178

A Commodore Gotcha

M. G. Ryschkewitsch and M. V. Barnhill

For all Commodore computers, a short hint on how to prevent a hidden error when writing or reading data files to tape or disk.

From the time you first began to learn algebra, you were taught that if X = Y and Y = Z then X = Y. This may seem trivial to you, but the problem is that your PET, VIC, or 64 doesn't always see things this way. However, this state of computer confusion doesn't happen often and is easily taken care of if you know to look for it.

Try typing in and running this disk program (tape users, see below):

10 CLOSE 1 : OPEN 1, 8, 15, "S0 : TEST" : CLOSE 1
20 OPEN 8, 8, 8, "0 : TEST, S, W"
30 X = 1/3 : Y =.333333333
40 PRINT"{CLEAR}" ;X; Y; X-Y
50 PRINT #8, X; ","; Y; CHR$(13);
60 CLOSE 8 : OPEN 8, 8, 8, "0 : TEST, S, R"
70 INPUT#8, X, Y : CLOSE 8
80 PRINT X; Y; X-Y

If you hadn't thought carefully about what your Commodore computer does with numbers, you were probably surprised that you didn't get the same result both times. What happened? Well, when the computer writes a number to the disk, it sends character by character exactly what it would write to the screen if you asked it to print that number (all of these comments also apply to tape files).

Since the internal operations are carried out with more significant figures than those displayed on the screen or printed to the data file, you can get a truncation error when doing operations with data from a disk file. In cases where the display uses less than the full number of digits because of trailing zeros, there will be no problem (try replacing the 1/3 with 1/2 and .333333333 with .500000000).

You should watch out for this problem if you are comparing numbers written to a data file to numbers kept in memory (for example, if you store temporary results from calculations or try to verify that data has been written properly to a data file). These situations can be handled by comparing STR$(number in memory) to STR$ (number from the disk). This comparison will not give an error if the numbers were the same to start with, but of course there is no guarantee that the numbers were not slightly different. At least your program will not crash unnecessarily.

Tape Version

10 OPEN 1, 1, 1, "TEST"
20 X = 1/3 : Y = .333333333
50 PRINT#1, X;","; Y; CHR$(13);
60 CLOSE 1
90 OPEN 1, 1, 0, "TEST"
100 INPUT #1, X, Y : CLOSE 1
110 PRINTX; Y; X-Y