So, straight to the point. I'm using AppleSoft BASIC, but there is some trouble with the SQR function. It seems that it produces integers when working with smaller perfect squares, but floats when working with bigger ones. For example:
I have this piece of code that tests if a variable is an integer, and prints "OK" if so:
] IF INT(X) = X THEN PRINT "OK"
When X
is defined as
] X = SQR(16)
] PRINT X
4
the function prints OK
.
However, when X
is defined as
] X = SQR(7744)
] PRINT X
88
the function doesn't print anything.
(Please note that ]
is the prompt and is not included in the code.)
Absurd, isn't it? I was able to reproduce it every time on my personal Apple //e, so you should be able to reproduce it on yours too. (It's 1986! Everyone should have one.)
Is it possible for SQR to produce a consistent result? Is there some kind of internal difference underneath SQR(16) and SQR(7744)?
P.S. I was a user on S.O. for over a year already, but somehow my account had disappeared. So no, I'm not just "starting out".
I've dug up some evidence/history. From my copy of the Basic Programming Manual Applesoft ][ (1978, Apple Computer Inc.) - with a bit of emphasis added in places:
p18:
REAL, INTEGER AND STRING VARIABLES
There are three different types of variables used in APPLESOFT BASIC. So far we have just used one type — real precision. Numbers in this mode are displayed with up to nine decimal digits of accuracy and may range up to approximately 10 to the 38th power. APPLESOFT converts your numbers from decimal to binary for its internal use and then back to decimal when you ask it to PRINT the answer. Because of rounding errors and other unpredictables , internal math routines such as square root, divide, and exponent do not always give the exact number that you expected.
All arithmetic operations are done in real precision. Integers and integer variable values are converted to real precision before they are used in a calculation. The functions SIN, COS, ATN, TAN, SQR, LOG, EXP and RND also convert their arguments to real precision and give their results as such.
p102:
SQR (aexpr) Returns the positive square root. This is a special implementation that executes more quickly than ^.5
So, I think you may have uncovered some of the "math routines such as square root ... do not always give the exact number that you expected" behavior within your function.
The note that SQR is a "special implementation" optimized for speed seems to imply that there might be something going on under the hood that could lead to errors.