BASIC: scientific functions and OPTION ANGLE DEGREES

ASIN, ACOS, ANGLE, SEC, CSC, COT; SINH, COSH, TANH and their inverses;
LOG10, LOG2; IP, FP, CEIL, ROUND, TRUNCATE; MOD; MIN and MAX of any number of
values; FACT; PI, DEG, RAD; OPTION ANGLE DEGREES|RADIANS. Out-of-domain values
give ILLEGAL FUNCTION CALL. basic/test-math.py checks each against Python's
math (within 3 ulp); the manual and README cover them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
brad ArantandClaude Opus 5.5 committed 2026-12-01 16:39:29 -08:00
1 parent 79aef8ed38
commit 25c8286cf2
8 files changed
+2985 -2375

No files matched your search

BIN
View File
Binary file not shown.
+131 -6
View File
@@ -180,6 +180,7 @@ static struct chan ch[NCHAN];
static struct chan *chan_arg(u8 mode);
static u8 chan_line(struct chan *c);
static u8 deg; /* OPTION ANGLE DEGREES */
static u8 ghi; /* 640x480 (SCREEN 1) */
static u16 gw = 320, gh = 240; /* the graphics' size */
/* follow the hardware's mode: a game run with CALL may have ended SCREEN 1 */
@@ -194,8 +195,12 @@ enum {
T_SAVE, T_LOAD, T_DIR, T_DEL, T_DATE, T_OPEN, T_CLOSE, T_MONITOR, T_CALL, T_BSAVE, T_BLOAD, T_OUTPUT, T_APPEND, T_AND, T_OR, T_NOT, T_SIN, T_COS, T_TAN, T_ATN, T_EXP, T_LOG, T_ABS,
T_SQR, T_INT, T_RND, T_SGN, T_FN, T_TAB, T_PEEK, T_INP, T_LEN, T_VAL, T_ASC, T_EOF,
T_CHRS, T_STRS, T_LEFTS, T_RIGHTS, T_MIDS, T_DATES, T_TIM, T_POINT, T_LE, T_GE, T_NE, T_RENUM,
T_DO, T_LOOP, T_WHILE, T_UNTIL, T_EXIT, T_ELSE, T_SELECT, T_CASE, T_LAST
T_DO, T_LOOP, T_WHILE, T_UNTIL, T_EXIT, T_ELSE, T_SELECT, T_CASE,
T_OPTION, T_PI, T_ANGLE, T_DEG, T_RAD, T_ASIN, T_ACOS, T_SEC, T_CSC, T_COT,
T_SINH, T_COSH, T_TANH, T_ASINH, T_ACOSH, T_ATANH, T_LOG10, T_LOG2, T_CEIL,
T_IP, T_FP, T_ROUND, T_TRUNCATE, T_MOD, T_MIN, T_MAX, T_FACT, T_LAST
};
_Static_assert(T_LAST <= 0x100, "too many keywords for a byte");
static const char *const kw[] = {
"LET", "PRINT", "INPUT", "IF", "THEN", "GOTO", "GOSUB", "RETURN", "FOR",
@@ -205,7 +210,10 @@ static const char *const kw[] = {
"SAVE", "LOAD", "DIR", "DEL", "DATE", "OPEN", "CLOSE", "MONITOR", "CALL", "BSAVE", "BLOAD", "OUTPUT", "APPEND", "AND", "OR", "NOT", "SIN", "COS", "TAN", "ATN", "EXP", "LOG", "ABS",
"SQR", "INT", "RND", "SGN", "FN", "TAB", "PEEK", "INP", "LEN", "VAL", "ASC", "EOF",
"CHR$", "STR$", "LEFT$", "RIGHT$", "MID$", "DATE$", "TIM", "POINT", "<=", ">=", "<>", "RENUM",
"DO", "LOOP", "WHILE", "UNTIL", "EXIT", "ELSE", "SELECT", "CASE"
"DO", "LOOP", "WHILE", "UNTIL", "EXIT", "ELSE", "SELECT", "CASE",
"OPTION", "PI", "ANGLE", "DEG", "RAD", "ASIN", "ACOS", "SEC", "CSC", "COT",
"SINH", "COSH", "TANH", "ASINH", "ACOSH", "ATANH", "LOG10", "LOG2", "CEIL",
"IP", "FP", "ROUND", "TRUNCATE", "MOD", "MIN", "MAX", "FACT"
};
/* ----------------------------------------------------------------- memory */
@@ -588,6 +596,7 @@ static void clear_vars(void)
arr_low = arena + ARENA;
nfor = nsub = ndo = 0;
datap = 0;
deg = 0;
}
static void new_prog(void)
@@ -769,6 +778,106 @@ static float rnd(void)
return (float)((seed >> 8) & 0xFFFFFF) / 16777216.0f;
}
/* ------------------------------------------------- scientific functions */
#define PI_F 3.14159265358979f
/* an angle from an inverse function, in the units OPTION ANGLE chose */
static float ang(float r) { return deg ? r * 180.0f / PI_F : r; }
/* sine (c = 0) or cosine (c = 1). In degrees, the angle is reduced exactly
to within 45 of a multiple of 90 first, so SIN(180) and COS(90) are 0. */
static float sin_cos(float v, u8 c)
{
float r, y;
int k;
if (!deg) return c ? cosf(v) : sinf(v);
r = fmodf(v, 360.0f);
k = (int)floorf(r / 90.0f + 0.5f);
r = (r - 90.0f * (float)k) * (PI_F / 180.0f);
k += c; /* cos x = sin(x + 90) */
y = k & 1 ? cosf(r) : sinf(r);
return (k & 2 ? -y : y) + 0.0f; /* + 0: no -0 */
}
/* x rounded (or truncated) to n decimal places, n < 0 to the left of the
point: INT(x * 10^n + .5) / 10^n, as in True BASIC */
static float round_to(float x, i16 n, u8 rnd)
{
float p = 1, s;
i16 i;
if (n < -38 || n > 38) error(E_FUNC);
for (i = n < 0 ? -n : n; i; i--) p *= 10.0f;
s = n < 0 ? x / p : x * p;
if (s >= 8388608.0f || s <= -8388608.0f) return x; /* nothing to round */
s = rnd ? floorf(s + 0.5f) : s < 0 ? -floorf(-s) : floorf(s);
return (n < 0 ? s * p : s / p) + 0.0f;
}
static float func2(u8 t, float v)
{
float w;
i16 n = 0;
u8 i;
switch (t) {
case T_ANGLE: /* ANGLE(x, y): the direction of (x, y) */
expect(',');
w = expr();
expect(')');
if (v == 0 && w == 0) error(E_FUNC);
return ang(atan2f(w, v));
case T_ROUND: case T_TRUNCATE:
if (t == T_TRUNCATE || peekc() == ',') { expect(','); n = to_int(expr()); }
expect(')');
return round_to(v, n, t == T_ROUND);
case T_MOD: /* the sign of the divisor, like INT */
expect(',');
w = expr();
expect(')');
if (w == 0) error(E_DIV0);
v = fmodf(v, w);
if (v != 0 && (v < 0) != (w < 0)) v += w;
return v + 0.0f;
case T_MIN: case T_MAX:
while (accept(',')) {
w = expr();
if (t == T_MIN ? w < v : w > v) v = w;
}
expect(')');
return v;
}
expect(')');
switch (t) {
case T_DEG: return v * 180.0f / PI_F;
case T_RAD: return v * PI_F / 180.0f;
case T_ASIN: if (v < -1 || v > 1) error(E_FUNC); return ang(asinf(v));
case T_ACOS: if (v < -1 || v > 1) error(E_FUNC); return ang(acosf(v));
case T_SEC: w = sin_cos(v, 1); if (w == 0) error(E_FUNC); return 1 / w;
case T_CSC: w = sin_cos(v, 0); if (w == 0) error(E_FUNC); return 1 / w;
case T_COT:
if (!deg) { w = tanf(v); if (w == 0) error(E_FUNC); return 1 / w; }
w = sin_cos(v, 0);
if (w == 0) error(E_FUNC);
return sin_cos(v, 1) / w;
case T_SINH: return sinhf(v);
case T_COSH: return coshf(v);
case T_TANH: return tanhf(v);
case T_ASINH: return asinhf(v);
case T_ACOSH: if (v < 1) error(E_FUNC); return acoshf(v);
case T_ATANH: if (v <= -1 || v >= 1) error(E_FUNC); return atanhf(v);
case T_LOG10: if (v <= 0) error(E_FUNC); return log10f(v);
case T_LOG2: if (v <= 0) error(E_FUNC); return log2f(v);
case T_CEIL: return -floorf(-v) + 0.0f;
case T_IP: return (v < 0 ? -floorf(-v) : floorf(v)) + 0.0f;
case T_FP: return v - (v < 0 ? -floorf(-v) : floorf(v));
case T_FACT: /* to 34!: 35! is beyond single precision */
if (v < 0 || v > 34 || v != floorf(v)) error(E_FUNC);
for (w = 1, i = 2; i <= v; i++) w *= i; /* exact to 13! */
return w;
}
error(E_SYNTAX);
return 0;
}
static float func(u8 t)
{
char s[STRMAX];
@@ -806,12 +915,19 @@ static float func(u8 t)
return *p ? parse_num(&p) : 0;
}
v = expr();
if (t >= T_ANGLE) return func2(t, v);
expect(')');
switch (t) {
case T_SIN: return sinf(v);
case T_COS: return cosf(v);
case T_TAN: return tanf(v);
case T_ATN: return atanf(v);
case T_SIN: return sin_cos(v, 0);
case T_COS: return sin_cos(v, 1);
case T_TAN:
if (deg) {
float c = sin_cos(v, 1);
if (c == 0) error(E_FUNC);
return sin_cos(v, 0) / c;
}
return tanf(v);
case T_ATN: return ang(atanf(v));
case T_EXP: return expf(v);
case T_LOG: if (v <= 0) error(E_FUNC); return logf(v);
case T_ABS: return v < 0 ? -v : v;
@@ -862,6 +978,8 @@ static float primary(void)
if (is_str_start()) error(E_TYPE);
if (c == T_FN) { tp++; return call_fn(); }
if (c >= T_SIN && c <= T_POINT && c != T_FN && c != T_TAB) { tp++; return func(c); }
if (c == T_PI) { tp++; return PI_F; }
if (c >= T_ANGLE && c <= T_FACT) { tp++; return func(c); }
if (is_alpha(c)) return *num_ref();
error(E_SYNTAX);
return 0;
@@ -2445,6 +2563,13 @@ static void statement(void)
running = 0;
break;
case T_DO: st_do(); break;
case T_OPTION: /* OPTION ANGLE DEGREES | RADIANS */
expect(T_ANGLE);
if (accept(T_DEG)) deg = 1;
else if (accept(T_RAD)) deg = 0;
else error(E_SYNTAX);
while (is_alpha(*tp)) tp++; /* the rest of the word */
break;
case T_LOOP: st_loop(); break;
case T_EXIT: st_exit(); break;
case T_SELECT: st_select(); break;
+2360 -2360
View File
File diff suppressed because it is too large. Load diff
+281
View File
@@ -0,0 +1,281 @@
#!/usr/bin/env python3
"""Check BASIC's scientific functions in tools/rv32emu.py.
python3 test-math.py [count]
First the maths library itself: each function in basic.bin (lib/mathf.c) is
called directly in the emulator, on random values across its range and on
the awkward ones, and its result compared bit for bit with Python's math
module (in double precision, so as good as exact here), in units in the last
place of single precision. Then BASIC: the functions as statements see them,
OPTION ANGLE DEGREES, and the errors outside each function's domain.
"""
import importlib.util
import math
import os
import random
import struct
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
spec = importlib.util.spec_from_file_location("te", os.path.join(HERE, "test-edit.py"))
te = importlib.util.module_from_spec(spec)
spec.loader.exec_module(te)
CR = te.CR
RET = 0x12000 # the machine-code area: a return address never run
STACK = 0x12FF0
def f32(x):
return struct.unpack("<f", struct.pack("<f", x))[0]
def bits(x):
return struct.unpack("<I", struct.pack("<f", x))[0]
def unbits(i):
return struct.unpack("<f", struct.pack("<I", i & 0xFFFFFFFF))[0]
def ulp(x):
"""Single precision's unit in the last place at x."""
x = abs(x)
if x < 2.0 ** -126:
return 2.0 ** -149
return 2.0 ** (math.floor(math.log2(x)) - 23)
def ulps(got, want):
if math.isinf(want):
return 0 if got == want else math.inf
w = f32(want) if abs(want) < 3.4e38 else want
if math.isinf(w):
return 0 if math.isinf(got) and (got > 0) == (want > 0) else math.inf
return abs(got - want) / ulp(want)
def symbols():
s = {}
for line in open(os.path.join(HERE, "out", "basic.sym")):
a, t, n = line.split()
s[n] = int(a, 16)
return s
class Caller:
"""Call a float function in basic.bin, ilp32f: arguments in fa0, fa1."""
def __init__(self, board):
self.b = board
self.sym = symbols()
def __call__(self, name, *args):
b = self.b
x, f, pc = b.x[:], b.f[:], b.pc
for i, a in enumerate(args):
b.f[10 + i] = bits(a)
b.x[1] = RET
b.x[2] = STACK
b.pc = self.sym[name]
n = 0
while b.pc != RET:
b.step()
n += 1
if n > 100000:
raise RuntimeError(name + " did not return")
r = unbits(b.f[10])
b.x[:], b.f[:], b.pc = x, f, pc
return r
def logspace(rng, lo, hi, n, signed=False):
"""n random floats with magnitudes spread evenly in log between lo and hi"""
out = []
for _ in range(n):
v = f32(math.exp(rng.uniform(math.log(lo), math.log(hi))))
out.append(-v if signed and rng.random() < 0.5 else v)
return out
def main():
count = int(sys.argv[1]) if len(sys.argv) > 1 else 1500
rng = random.Random(1)
b = te.Basic()
b.type(b"")
call = Caller(b)
errors = 0
def check(what, ok, out=""):
nonlocal errors
print(("PASS " if ok else "FAIL ") + what)
if not ok and out:
print(out)
errors += not ok
def uni(lo, hi, n):
return [f32(rng.uniform(lo, hi)) for _ in range(n)]
# name, reference, inputs, the most ulps allowed
n = count
tests = [
("asinf", math.asin, uni(-1, 1, n) + logspace(rng, 1e-30, 1, n, True) + [1, -1, 0.5, 1 - 2 ** -24], 3),
("acosf", math.acos, uni(-1, 1, n) + logspace(rng, 1e-30, 1, n, True) + [1, -1, 0, 1 - 2 ** -24, -1 + 2 ** -24], 3),
("sinhf", math.sinh, uni(-12, 12, n) + logspace(rng, 1e-30, 89, n, True) + [1, -1, 10, 89.4], 3),
("coshf", math.cosh, uni(-12, 12, n) + logspace(rng, 1e-30, 89, n, True) + [0, 1, 10, 89.4], 3),
("tanhf", math.tanh, uni(-12, 12, n) + logspace(rng, 1e-30, 30, n, True) + [0, 1, 10, -10], 3),
("asinhf", math.asinh, uni(-10, 10, n) + logspace(rng, 1e-30, 3e38, n, True) + [0, 1, 1e9, 2e9], 3),
("acoshf", math.acosh, [1 + abs(v) for v in uni(0, 10, n)] + logspace(rng, 1, 3e38, n)
+ [1 + 2 ** -23 * k for k in range(1, 40)] + [1, 1e9, 2e9], 3),
("atanhf", math.atanh, uni(-1, 1, n) + logspace(rng, 1e-30, 1, n, True)
+ [1 - 2 ** -24 * k for k in range(1, 40)] + [0, 0.5], 3),
("log1pf", math.log1p, logspace(rng, 1e-30, 1e30, n) + uni(-0.999, 1, n), 3),
("log10f", math.log10, logspace(rng, 1e-45, 3e38, n) + uni(0.5, 2, n) + [10.0 ** k for k in range(-37, 39)], 2),
("log2f", math.log2, logspace(rng, 1e-45, 3e38, n) + uni(0.5, 2, n), 2),
]
for name, ref, xs, most in tests:
worst, at = 0, None
for x in xs:
x = f32(x)
try:
want = ref(x)
except (ValueError, OverflowError):
want = math.inf if name in ("sinhf", "coshf") else None
if name == "sinhf":
want = math.copysign(math.inf, x)
if want is None:
continue
e = ulps(call(name, x), want)
if e > worst:
worst, at = e, x
check(f"{name}: {len(xs)} values, worst {worst:.2f} ulp (at {at!r}), "
f"allowed {most}", worst <= most)
# exact cases
check("log2f exact at powers of 2", all(call("log2f", 2.0 ** k) == k for k in range(-149, 128)))
check("asinf(1), acosf(-1), acosf(1) exact",
call("asinf", 1.0) == f32(math.pi / 2) and call("acosf", -1.0) == f32(math.pi)
and call("acosf", 1.0) == 0)
# atan2f
worst, at = 0, None
for _ in range(4 * n):
y, x = f32(rng.uniform(-10, 10)), f32(rng.uniform(-10, 10))
if rng.random() < 0.3:
y = f32(y * 10 ** rng.uniform(-20, 20))
e = ulps(call("atan2f", y, x), math.atan2(y, x))
if e > worst:
worst, at = e, (y, x)
axes = all(call("atan2f", y, x) == f32(math.atan2(y, x))
for y, x in [(0, 1), (1, 0), (0, -1), (-1, 0), (1, 1), (-1, -1)])
check(f"atan2f: {4 * n} values, worst {worst:.2f} ulp (at {at!r}), allowed 3; axes exact",
worst <= 3 and axes)
# fmodf must be exact
bad = []
for _ in range(4 * n):
x = f32(rng.choice([-1, 1]) * 10 ** rng.uniform(-10, 30))
y = f32(rng.choice([-1, 1]) * 10 ** rng.uniform(-10, 10))
if call("fmodf", x, y) != f32(math.fmod(x, y)):
bad.append((x, y))
check(f"fmodf exact on {4 * n} values", not bad, repr(bad[:5]))
# ---------------------------------------------------------------- BASIC
def screen():
return "\n".join(l.rstrip() for l in b.screen_text().display)
def run(prog):
b.type(b"NEW" + CR)
b.type(b"CLS" + CR)
for line in prog.strip().splitlines():
b.type(line.encode() + CR)
b.type(b"RUN" + CR)
return screen().split("RUN")[-1]
def rows(out):
return [l.strip() for l in out.splitlines() if l.strip() and l.strip() != "READY"]
out = run('''
10 PRINT PI; DEG(PI); RAD(180); ATN(1) * 4
20 PRINT ASIN(.5); ACOS(-1); ANGLE(-1, 0); ANGLE(0, -2)
30 PRINT SINH(1); COSH(1); TANH(.5); ASINH(1); ACOSH(2); ATANH(.5)
40 PRINT LOG10(1000); LOG2(1024); LOG10(2); LOG(EXP(2))
50 PRINT SEC(0); CSC(PI / 2); COT(PI / 4)
''')
got = rows(out)
want = ["3.14159 180 3.14159 3.14159",
".523599 3.14159 3.14159 -1.5708",
"1.1752 1.54308 .462117 .881374 1.31696 .549306",
"3 10 .30103 2",
"1 1 1"]
check("PI, DEG, RAD, the inverse trig functions, ANGLE", got[:2] == want[:2], out)
check("hyperbolic functions and their inverses", got[2:3] == want[2:3], out)
check("LOG10, LOG2", got[3:4] == want[3:4], out)
check("SEC, CSC, COT", got[4:5] == want[4:5], out)
out = run('''
10 PRINT ROUND(2.567, 2); ROUND(2.5); ROUND(-2.5); ROUND(1250, -2); ROUND(-1.25, 1)
20 PRINT TRUNCATE(2.567, 1); TRUNCATE(-2.567, 1); TRUNCATE(1299, -2)
30 PRINT IP(3.7); IP(-3.7); FP(3.75); FP(-3.75); CEIL(3.2); CEIL(-3.2); CEIL(4)
40 PRINT MOD(7, 3); MOD(-7, 3); MOD(7, -3); MOD(-7, -3); MOD(7.5, 2); MOD(6, 3)
50 PRINT MIN(3, 1, 2); MAX(3, 1, 2); MIN(-1, -5); MAX(4)
60 PRINT FACT(0); FACT(5); FACT(10); FACT(13); FACT(34)
''')
got = rows(out)
want = ["2.57 3 -2 1300 -1.2",
"2.5 -2.5 1200",
"3 -3 .75 -.75 4 -3 4",
"1 2 -2 -1 1.5 0",
"1 3 -5 4",
"1 120 3.6288E+06 6.22702E+09 2.95233E+38"]
for w, g, what in zip(want, got + [""] * 6,
["ROUND", "TRUNCATE", "IP, FP, CEIL", "MOD", "MIN, MAX", "FACT"]):
check(what, g == w, f"got {g!r}, want {w!r}")
out = run('''
10 OPTION ANGLE DEGREES
20 PRINT SIN(30); SIN(180); COS(90); COS(60); TAN(45); SIN(-90); COS(720)
30 PRINT ASIN(1); ACOS(0); ATN(1); ANGLE(-1, -1); SEC(60); COT(45); CSC(30)
40 PRINT SIN(1E6); COS(-123.5)
50 OPTION ANGLE RADIANS
60 PRINT SIN(PI / 6); ATN(1)
''')
got = rows(out)
check("OPTION ANGLE DEGREES: exact at multiples of 30 and 45",
got[:2] == [".5 0 0 .5 1 -1 1", "90 90 45 -135 2 1 2"], out)
try:
big = [float(v) for v in got[2].split()]
except (IndexError, ValueError):
big = []
check("degrees: large and negative angles",
len(big) == 2 and abs(big[0] - math.sin(math.radians(1e6))) < 2e-6
and abs(big[1] - math.cos(math.radians(-123.5))) < 2e-6, out)
check("OPTION ANGLE RADIANS goes back", got[3:4] == [".5 .785398"], out)
out = run('10 PRINT SIN(90)')
check("RUN starts in radians again", rows(out) == [".893997"], out)
for expr, msg in [("ASIN(1.5)", "ILLEGAL"), ("ACOS(-2)", "ILLEGAL"), ("ACOSH(.5)", "ILLEGAL"),
("ATANH(1)", "ILLEGAL"), ("ATANH(-1)", "ILLEGAL"), ("LOG10(0)", "ILLEGAL"),
("LOG2(-1)", "ILLEGAL"), ("FACT(-1)", "ILLEGAL"), ("FACT(2.5)", "ILLEGAL"),
("FACT(35)", "ILLEGAL"), ("ANGLE(0, 0)", "ILLEGAL"), ("MOD(1, 0)", "DIVISION BY ZERO"),
("ROUND(1, 39)", "ILLEGAL"), ("CSC(0)", "ILLEGAL"), ("COT(0)", "ILLEGAL")]:
out = run(f"10 PRINT {expr}")
check(f"{expr} is an error", msg in out, out)
out = run("10 OPTION ANGLE DEGREES: PRINT TAN(90)")
check("TAN(90) in degrees is an error", "ILLEGAL" in out, out)
out = run("10 OPTION ANGLE DEGREES: PRINT SEC(90)")
check("SEC(90) in degrees is an error", "ILLEGAL" in out, out)
out = run("10 OPTION ANGLE GRADS")
check("OPTION ANGLE wants DEGREES or RADIANS", "SYNTAX" in out, out)
b.type(b"NEW" + CR)
b.type(b"CLS" + CR)
b.type(b"10 OPTION ANGLE DEGREES: X = TRUNCATE(PI, 3)" + CR)
b.type(b"LIST" + CR)
check("LIST spells the new words as typed",
"10 OPTION ANGLE DEGREES: X = TRUNCATE(PI, 3)" in screen(), screen())
sys.exit(1 if errors else 0)
if __name__ == "__main__":
main()