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:
1 parent
79aef8ed38
commit
25c8286cf2
8 files changed
+2985
-2375
No files matched your search
@@ -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()
|
||||
Reference in new issue
Block a user