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 0cb1eafaa3
8 files changed
+2985 -2375

No files matched your search

+8 -4
View File
@@ -14,8 +14,10 @@ RISC-V processor written from scratch in Verilog:
- **USB keyboard** on the board's USB host port, with a keys-held port for - **USB keyboard** on the board's USB host port, with a keys-held port for
games. games.
- **Files** saved in the board's configuration flash. - **Files** saved in the board's configuration flash.
- **Software**: Dartmouth-style BASIC with graphics, sound and files, and - **Software**: Dartmouth-style BASIC with graphics, sound and files,
`DO … LOOP`, block `IF … ELSE … END IF` and `SELECT CASE`; a `DO … LOOP`, block `IF … ELSE … END IF` and `SELECT CASE`, and scientific
functions (inverse and hyperbolic trigonometry in radians or degrees,
`LOG10`, `ROUND`, `MOD`, `FACT` …); a
machine-code monitor with a RISC-V disassembler and assembler, and five machine-code monitor with a RISC-V disassembler and assembler, and five
original games. original games.
@@ -156,7 +158,9 @@ All in C (plus a little assembly), compiled with GCC:
`ilp32f`), correctly rounded, and the structured statements of later `ilp32f`), correctly rounded, and the structured statements of later
Dartmouth BASIC and True BASIC (`DO … LOOP`, `EXIT`, block `IF`, `SELECT Dartmouth BASIC and True BASIC (`DO … LOOP`, `EXIT`, block `IF`, `SELECT
CASE`). `lib/` has the few C library functions it CASE`). `lib/` has the few C library functions it
needs (small string functions, `setjmp`, and `sinf` … `sqrtf`), since needs (small string functions, `setjmp`, and `sinf` … `sqrtf`, `asinf`,
`sinhf`, `atanhf`, `log10f`, an exact `fmodf` and the rest, each within 3
ulp), since
newlib's bring in its stdio and malloc. newlib's bring in its stdio and malloc.
- `monitor/` — the machine-code monitor: memory, registers (integer and - `monitor/` — the machine-code monitor: memory, registers (integer and
floating point), step, breakpoints, a RISC-V disassembler and a two-pass floating point), step, breakpoints, a RISC-V disassembler and a two-pass
@@ -196,7 +200,7 @@ the configuration flash.
| `scripts/cputest.sh` | the official [riscv-tests](https://github.com/riscv-software-src/riscv-tests) (`rv32ui`, `rv32um`, `rv32uf`, `rv32mi`, fetched into `third_party/`) and `tests/` (interrupts, the NMI and single step) on `rv32_cpu.v` in xsim, with random wait states on the data bus. Two riscv-tests don't apply: `ma_data` expects misaligned loads and stores to work (here they trap, as the spec allows) and `pmpaddr` needs PMP. | | `scripts/cputest.sh` | the official [riscv-tests](https://github.com/riscv-software-src/riscv-tests) (`rv32ui`, `rv32um`, `rv32uf`, `rv32mi`, fetched into `third_party/`) and `tests/` (interrupts, the NMI and single step) on `rv32_cpu.v` in xsim, with random wait states on the data bus. Two riscv-tests don't apply: `ma_data` expects misaligned loads and stores to work (here they trap, as the spec allows) and `pmpaddr` needs PMP. |
| `scripts/sim.sh` | the whole design in xsim: the terminal, BASIC, both graphics modes, sprites, scrolling, flash files, the monitor (step, breakpoint, Pause, memory files, the assembler, Intel HEX), 3 Mbaud. `scripts/sim.sh quick` skips the terminal and the monitor; `wide` checks the 132 × 64 start-up. | | `scripts/sim.sh` | the whole design in xsim: the terminal, BASIC, both graphics modes, sprites, scrolling, flash files, the monitor (step, breakpoint, Pause, memory files, the assembler, Intel HEX), 3 Mbaud. `scripts/sim.sh quick` skips the terminal and the monitor; `wide` checks the 132 × 64 start-up. |
| `monitor/test-disasm.py`, `test-asm.py` | the disassembler against GNU objdump on thousands of random instructions, and the assembler against GNU as | | `monitor/test-disasm.py`, `test-asm.py` | the disassembler against GNU objdump on thousands of random instructions, and the assembler against GNU as |
| `basic/test-*.py`, `games/*/test-*.py` | BASIC's line editor, RENUM, string arrays, block structures and graphics modes, and each game, on `tools/rv32emu.py` (a Python RV32IMF emulator of the machine; `tools/boardemu.py` models the game hardware). They need `pyte` and Pillow. | | `basic/test-*.py`, `games/*/test-*.py` | BASIC's line editor, RENUM, string arrays, block structures, graphics modes and maths functions (bit for bit against Python's `math`), and each game, on `tools/rv32emu.py` (a Python RV32IMF emulator of the machine; `tools/boardemu.py` models the game hardware). They need `pyte` and Pillow. |
| `bench/` | the processor alone with 64 KB of RAM, for timing | | `bench/` | the processor alone with 64 KB of RAM, for timing |
## Toolchain ## Toolchain
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 struct chan *chan_arg(u8 mode);
static u8 chan_line(struct chan *c); static u8 chan_line(struct chan *c);
static u8 deg; /* OPTION ANGLE DEGREES */
static u8 ghi; /* 640x480 (SCREEN 1) */ static u8 ghi; /* 640x480 (SCREEN 1) */
static u16 gw = 320, gh = 240; /* the graphics' size */ static u16 gw = 320, gh = 240; /* the graphics' size */
/* follow the hardware's mode: a game run with CALL may have ended SCREEN 1 */ /* 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_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_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_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[] = { static const char *const kw[] = {
"LET", "PRINT", "INPUT", "IF", "THEN", "GOTO", "GOSUB", "RETURN", "FOR", "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", "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", "SQR", "INT", "RND", "SGN", "FN", "TAB", "PEEK", "INP", "LEN", "VAL", "ASC", "EOF",
"CHR$", "STR$", "LEFT$", "RIGHT$", "MID$", "DATE$", "TIM", "POINT", "<=", ">=", "<>", "RENUM", "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 */ /* ----------------------------------------------------------------- memory */
@@ -588,6 +596,7 @@ static void clear_vars(void)
arr_low = arena + ARENA; arr_low = arena + ARENA;
nfor = nsub = ndo = 0; nfor = nsub = ndo = 0;
datap = 0; datap = 0;
deg = 0;
} }
static void new_prog(void) static void new_prog(void)
@@ -769,6 +778,106 @@ static float rnd(void)
return (float)((seed >> 8) & 0xFFFFFF) / 16777216.0f; 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) static float func(u8 t)
{ {
char s[STRMAX]; char s[STRMAX];
@@ -806,12 +915,19 @@ static float func(u8 t)
return *p ? parse_num(&p) : 0; return *p ? parse_num(&p) : 0;
} }
v = expr(); v = expr();
if (t >= T_ANGLE) return func2(t, v);
expect(')'); expect(')');
switch (t) { switch (t) {
case T_SIN: return sinf(v); case T_SIN: return sin_cos(v, 0);
case T_COS: return cosf(v); case T_COS: return sin_cos(v, 1);
case T_TAN: return tanf(v); case T_TAN:
case T_ATN: return atanf(v); 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_EXP: return expf(v);
case T_LOG: if (v <= 0) error(E_FUNC); return logf(v); case T_LOG: if (v <= 0) error(E_FUNC); return logf(v);
case T_ABS: return v < 0 ? -v : 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 (is_str_start()) error(E_TYPE);
if (c == T_FN) { tp++; return call_fn(); } 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_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(); if (is_alpha(c)) return *num_ref();
error(E_SYNTAX); error(E_SYNTAX);
return 0; return 0;
@@ -2445,6 +2563,13 @@ static void statement(void)
running = 0; running = 0;
break; break;
case T_DO: st_do(); 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_LOOP: st_loop(); break;
case T_EXIT: st_exit(); break; case T_EXIT: st_exit(); break;
case T_SELECT: st_select(); 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()
+72 -4
View File
@@ -419,6 +419,16 @@ in its formula are the program's ordinary variables.
the program. A `DATA` statement takes up the rest of its line. `RESTORE` starts the program. A `DATA` statement takes up the rest of its line. `RESTORE` starts
again from the first item. again from the first item.
### OPTION ANGLE
```
OPTION ANGLE DEGREES
OPTION ANGLE RADIANS
```
Chooses the units of the trigonometric functions (section 6). Radians are
the default, and `RUN` goes back to them.
### END, STOP, REM ### END, STOP, REM
- `END` stops the program quietly. - `END` stops the program quietly.
@@ -460,16 +470,74 @@ and `INK` are described in sections 7 and 8.
| `ABS(X)` | Absolute value | | `ABS(X)` | Absolute value |
| `SGN(X)` | -1, 0 or 1 | | `SGN(X)` | -1, 0 or 1 |
| `INT(X)` | Largest whole number not above *X*: `INT(-2.5)` is -3 | | `INT(X)` | Largest whole number not above *X*: `INT(-2.5)` is -3 |
| `IP(X)` | The whole-number part, towards 0: `IP(-2.5)` is -2 |
| `FP(X)` | The fraction part, `X - IP(X)`: `FP(-2.5)` is -.5 |
| `CEIL(X)` | Smallest whole number not below *X*: `CEIL(2.1)` is 3 |
| `ROUND(X [, N])` | *X* rounded to *N* decimal places (0 if left out); a negative *N* rounds to tens, hundreds…: `ROUND(2.567, 2)` is 2.57, `ROUND(1250, -2)` is 1300. Halves go up, as `INT(X + .5)` does: `ROUND(-2.5)` is -2 |
| `TRUNCATE(X, N)` | *X* cut short after *N* decimal places: `TRUNCATE(-2.567, 1)` is -2.5 |
| `MOD(A, B)` | Remainder of *A* divided by *B*, with the sign of *B*: `A - B * INT(A / B)`, but exact. `MOD(-7, 3)` is 2 |
| `MIN(A, B, …)`, `MAX(A, B, …)` | Smallest or largest of any number of values |
| `FACT(N)` | *N* factorial, for whole numbers 0 to 34 |
| `SQR(X)` | Square root | | `SQR(X)` | Square root |
| `EXP(X)` | e to the power *X* | | `EXP(X)` | e to the power *X* |
| `LOG(X)` | Natural logarithm | | `LOG(X)` | Natural logarithm |
| `SIN(X)`, `COS(X)`, `TAN(X)` | Trigonometry, in radians | | `LOG10(X)`, `LOG2(X)` | Logarithm to base 10 or 2 (`LOG2` is exact for powers of 2); powers of 10 are `10 ^ X` |
| `ATN(X)` | Arctangent, in radians; `4*ATN(1)` is pi | | `PI` | 3.14159265 (no brackets) |
| `RND` or `RND(X)` | Random number from 0 up to (not including) 1; *X* is ignored | | `RND` or `RND(X)` | Random number from 0 up to (not including) 1; *X* is ignored |
| `FNx(X)` | A function made with `DEF` | | `FNx(X)` | A function made with `DEF` |
A whole number from 1 to 6: `1 + INT(RND * 6)`. A whole number from 1 to 6: `1 + INT(RND * 6)`.
### Trigonometry
| Function | Result |
|---|---|
| `SIN(X)`, `COS(X)`, `TAN(X)` | Sine, cosine, tangent |
| `SEC(X)`, `CSC(X)`, `COT(X)` | Secant, cosecant, cotangent: `1/COS(X)`, `1/SIN(X)`, `1/TAN(X)` |
| `ATN(X)` | Arctangent, from -90° to 90° (-π/2 to π/2) |
| `ASIN(X)`, `ACOS(X)` | Arcsine (-90° to 90°) and arccosine (0° to 180°), for *X* from -1 to 1 |
| `ANGLE(X, Y)` | The direction of the point (*X*, *Y*) from the origin, from -180° to 180°, measured anticlockwise from the X axis; it gets the quarter right, as `ATN(Y / X)` can't (other languages call it `ATAN2(Y, X)`) |
| `DEG(X)`, `RAD(X)` | Radians to degrees, degrees to radians |
| `SINH(X)`, `COSH(X)`, `TANH(X)` | Hyperbolic sine, cosine, tangent |
| `ASINH(X)`, `ACOSH(X)`, `ATANH(X)` | Their inverses: `ACOSH` for *X* ≥ 1, `ATANH` for *X* between -1 and 1 |
Angles are in radians until a program says `OPTION ANGLE DEGREES`; from
then on the trigonometric functions take degrees and the inverse ones
(`ATN`, `ASIN`, `ACOS`, `ANGLE`) give degrees. `OPTION ANGLE RADIANS` goes
back, and so does `RUN`. In degrees, `SIN`, `COS` and the rest are exact at
multiples of 90, so `SIN(180)` is 0, not a tiny remainder.
A value outside a function's range, such as `ASIN(2)`, `LOG10(0)`,
`ACOSH(0)`, `FACT(2.5)`, `ANGLE(0, 0)` or, in degrees, `TAN(90)`, stops
the program with `ILLEGAL FUNCTION CALL`; `MOD(A, 0)` is
`DIVISION BY ZERO`. Every function is correct to within 3 units in the last
place of single precision (about 1 part in 3 million), checked against a
PC's double-precision maths by `basic/test-math.py`.
```
10 OPTION ANGLE DEGREES
20 FOR A = 0 TO 75 STEP 15
30 PRINT A, ROUND(SIN(A), 4), ROUND(COS(A), 4), ROUND(TAN(A), 4)
40 NEXT A
50 PRINT "BEARING OF (3, 4):"; ROUND(ANGLE(3, 4), 2); "DEGREES"
60 PRINT "ITS HYPOTENUSE:"; SQR(3^2 + 4^2)
70 PRINT "ACOS(-1) ="; ACOS(-1); " 20! ="; FACT(20)
```
prints
```
0 0 1 0
15 .2588 .9659 .2679
30 .5 .866 .5774
45 .7071 .7071 1
60 .866 .5 1.7321
75 .9659 .2588 3.7321
BEARING OF (3, 4): 53.13 DEGREES
ITS HYPOTENUSE: 5
ACOS(-1) = 180 20! = 2.4329E+18
```
### Strings ### Strings
| Function | Result | | Function | Result |
@@ -1303,11 +1371,11 @@ An error stops the program and reports the line, for example
| `NEXT WITHOUT FOR` | `NEXT` with no loop open (or the wrong variable) | | `NEXT WITHOUT FOR` | `NEXT` with no loop open (or the wrong variable) |
| `OUT OF DATA` | `READ` after the last `DATA` item | | `OUT OF DATA` | `READ` after the last `DATA` item |
| `SUBSCRIPT OUT OF RANGE` | An array subscript below 0 or beyond its `DIM` | | `SUBSCRIPT OUT OF RANGE` | An array subscript below 0 or beyond its `DIM` |
| `DIVISION BY ZERO` | Dividing by 0 | | `DIVISION BY ZERO` | Dividing by 0, or `MOD(A, 0)` |
| `OUT OF MEMORY` | The program and arrays don't fit | | `OUT OF MEMORY` | The program and arrays don't fit |
| `TYPE MISMATCH` | A string where a number belongs, or the other way round | | `TYPE MISMATCH` | A string where a number belongs, or the other way round |
| `STRING TOO LONG` | A string over 79 characters, or a program line too long to store (also from `RENUM`) | | `STRING TOO LONG` | A string over 79 characters, or a program line too long to store (also from `RENUM`) |
| `ILLEGAL FUNCTION CALL` | A bad argument: `SQR(-1)`, `LOG(0)`, a colour over 15, `AND` on a number beyond ±32767, a file number other than 1–3, an impossible `DATE`, a `RENUM` past 65535 or with a step of 0 | | `ILLEGAL FUNCTION CALL` | A bad argument: `SQR(-1)`, `LOG(0)`, `ASIN(2)`, `FACT(-1)` (section 6), a colour over 15, `AND` on a number beyond ±32767, a file number other than 1–3, an impossible `DATE`, a `RENUM` past 65535 or with a step of 0 |
| `UNDEFINED FUNCTION` | `FNx` used before its `DEF` | | `UNDEFINED FUNCTION` | `FNx` used before its `DEF` |
| `FOR NESTED TOO DEEPLY` | More than 16 `FOR` loops open | | `FOR NESTED TOO DEEPLY` | More than 16 `FOR` loops open |
| `DO NESTED TOO DEEPLY` | More than 16 `DO` loops open | | `DO NESTED TOO DEEPLY` | More than 16 `DO` loops open |
Binary file not shown.
+133 -1
View File
@@ -1,5 +1,6 @@
/* Single-precision maths for BASIC: sinf cosf tanf atanf expf logf sqrtf /* Single-precision maths for BASIC: sinf cosf tanf atanf expf logf sqrtf
floorf. Range reduction by Cody and Waite, minimax polynomials as in the floorf, and from them asinf acosf atan2f sinhf coshf tanhf asinhf acoshf
atanhf log1pf log10f log2f and an exact fmodf. Range reduction by Cody and Waite, minimax polynomials as in the
Cephes library; good to an ulp or two, which BASIC's 6-7 printed digits Cephes library; good to an ulp or two, which BASIC's 6-7 printed digits
don't show. sqrtf (the FPU's FSQRT.S when there is one) and floorf are don't show. sqrtf (the FPU's FSQRT.S when there is one) and floorf are
exact. (newlib's versions are larger and exact. (newlib's versions are larger and
@@ -190,3 +191,134 @@ float floorf(float x)
else if (u.i << 1) u.f = -1.0f; else if (u.i << 1) u.f = -1.0f;
return u.f; return u.f;
} }
/* ------------------------------------------------- built on the above */
static const float PI_F = 3.14159265358979f, LN2_F = 0.693147180559945f;
/* log(1 + u), accurate for small u: Goldberg's trick, since w - 1 is exact */
float log1pf(float u)
{
float w = 1.0f + u;
if (w == 1.0f) return u;
return logf(w) * (u / (w - 1.0f));
}
float asinf(float x) /* |x| <= 1 */
{
return atanf(x / sqrtf((1.0f - x) * (1.0f + x)));
}
float acosf(float x) /* |x| <= 1 */
{
return 2.0f * atanf(sqrtf((1.0f - x) / (1.0f + x)));
}
float atan2f(float y, float x)
{
float a;
if (x == 0.0f) return y > 0 ? PI_F / 2 : y < 0 ? -PI_F / 2 : 0.0f;
a = atanf(y / x);
if (x < 0) a += y < 0 ? -PI_F : PI_F;
return a;
}
/* e^|x| / 2 for large |x|, without overflowing on the way */
static float half_exp(float a)
{
float h = expf(0.5f * a);
return (0.5f * h) * h;
}
float sinhf(float x)
{
float a = x < 0 ? -x : x, r, z, e;
if (a < 1.0f) { /* the series: no cancellation */
z = a * a;
r = a + a * z * (1.6666667163e-1f + z * (8.3333337680e-3f + z * (1.9841270114e-4f
+ z * (2.7557318845e-6f + z * 2.5052108385e-8f))));
} else if (a < 10.0f) {
e = expf(a);
r = 0.5f * (e - 1.0f / e);
} else r = half_exp(a);
return x < 0 ? -r : r;
}
float coshf(float x)
{
float a = x < 0 ? -x : x, e;
if (a >= 10.0f) return half_exp(a);
e = expf(a);
return 0.5f * (e + 1.0f / e);
}
float tanhf(float x)
{
float a = x < 0 ? -x : x, r;
r = a >= 10.0f ? 1.0f : sinhf(a) / coshf(a);
return x < 0 ? -r : r;
}
float asinhf(float x)
{
float a = x < 0 ? -x : x, r;
if (a > 1e9f) r = logf(a) + LN2_F;
else r = log1pf(a + a * a / (1.0f + sqrtf(1.0f + a * a)));
return x < 0 ? -r : r;
}
float acoshf(float x) /* x >= 1 */
{
float t;
if (x > 1e9f) return logf(x) + LN2_F;
t = x - 1.0f;
return log1pf(t + sqrtf(2.0f * t + t * t));
}
float atanhf(float x) /* |x| < 1 */
{
float a = x < 0 ? -x : x, r;
r = 0.5f * log1pf(2.0f * a / (1.0f - a));
return x < 0 ? -r : r;
}
/* log of x = m * 2^e, m in [sqrt(1/2), sqrt(2)): returns log(m), sets e */
static float log_split(float x, int *e)
{
fbits u = { x };
int k = 0;
if (u.i < 0x00800000) { u.f *= 16777216.0f; k = -24; } /* subnormal */
k += (int)(u.i >> 23) - 127;
u.i = (u.i & 0x007FFFFF) | 0x3F800000; /* [1, 2) */
if (u.f > 1.41421356f) { u.f *= 0.5f; k++; }
*e = k;
return logf(u.f);
}
float log2f(float x) /* x > 0: exact for powers of 2 */
{
int e;
float y = log_split(x, &e);
return y * 1.44269504088896341f + (float)e;
}
float log10f(float x) /* x > 0 */
{
int e;
float y = log_split(x, &e), f = (float)e;
/* log10(2) and log10(e) each split in two, as in Cephes */
return ((f * 2.48745663981195213739e-4f + y * 7.00731903251827651129e-4f)
+ y * 4.3359375e-1f) + f * 3.0078125e-1f;
}
/* exactly x - n*y, n = x/y truncated, by binary long division: each step
subtracts t from r with t <= r < 2t, which is exact */
float fmodf(float x, float y)
{
float r = x < 0 ? -x : x, d = y < 0 ? -y : y, t;
if (d == 0.0f || r < d) return x;
t = d;
while (t <= 0.5f * r) t += t;
for (; t >= d; t *= 0.5f)
if (r >= t) r -= t;
return x < 0 ? -r : r;
}