COMPUTE! ISSUE 37 / JUNE 1983 / PAGE 10
READERS'
FEEDBACK
Rounding Numbers
In using the simple program below, I encountered a (possible) bug in
Applesoft's handling of variables. After the program is RUN, and an
input of 3,4,5 is given (a known right triangle), I get an output of
"NO". When I PRINT X and D, I get 5 and 5, respectively. But when I
PRINT X = D, I get a response of zero, meaning "false." Is this a known
error, or is this a bug in my program?
Ken Carpenter
1 PRINT"THIS
PROGRAM WILL DETERMINE THE "
2
PRINT"PYTHAGOREAN TRIPLE"
3 PRINT"INPUT
3 NUMBERS"
10 INPUT A,B,D
40
X=SQR((A*A)+(B*B))
50 IF D=X THEN
INVERSE:PRINT"YES":GOTO 70
55 INVERSE
60 PRINT"NO"
70 NORMAL:GOTO
1
The problem that you speak of here is
common to most forms of BASIC and has to do with the manner in which
computers handle real numbers. A very small calculation error will
occur in some instances.
In your example,
the number that is calculated for X on the Apple is slightly more than
5 (5.000000002, actually). PRINT X-D to see this difference after
RUNning the program.
Before the Apple
prints a value for X, it rounds this number to 9 digits and drops
trailing zeroes so that 5.00000000 appears on your screen as 5.
Internally, the Apple stores this number with greater precision (Recall
that X was not equal to D in your example).
A way to get
around this problem is to convert numeric values to strings and then
compare the strings. In this way, the small calculation error is not
seen. In your program, line 50 would then read:
IF STR$(D)=STR$(X)
THEN INVERSE:PRINT"YES": GOTO 70