From 3967fccab7a41f8218b7ba589eee470d7ab4972a Mon Sep 17 00:00:00 2001 From: lemon Date: Sun, 15 Jun 2025 16:18:58 +0200 Subject: maths --- Makefile | 2 +- pez.c | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 1cc019b..4677bc2 100644 --- a/Makefile +++ b/Makefile @@ -12,7 +12,7 @@ opt: CFLAGS += -Oz opt: pez pez: repl.c pez.c pez.h - $(CC) -o$@ -lreadline $(CFLAGS) repl.c pez.c + $(CC) -o$@ -lm -lreadline $(CFLAGS) repl.c pez.c clean: $(RM) pez diff --git a/pez.c b/pez.c index 3f64b28..e12ad46 100644 --- a/pez.c +++ b/pez.c @@ -9,6 +9,7 @@ #include #include #include +#include #ifdef __GNUC__ #define FORCEINLINE __attribute__((always_inline)) @@ -2406,6 +2407,63 @@ f_ioclose(PezContext *cx, int argc) return 1; } +static bool +f_abs(PezContext *cx, int argc) +{ + PezNumber n; + TRY(pez_checksig(cx, argc, "abs", "number")); + pez_getnumber(cx, &n, -1); + return pez_pushnumber(cx, n < 0 ? -n : n); +} + +static bool +f_sqrt(PezContext *cx, int argc) +{ + PezNumber n; + TRY(pez_checksig(cx, argc, "sqrt", "number")); + pez_getnumber(cx, &n, -1); + return pez_pushnumber(cx, pez_ftonum(sqrtf(pez_numtof(n)))); +} + +static PezNumber +xsin(PezNumber x) +{ + static uint16_t lut[4096]; + PezNumber t; + bool neg; + + if (!lut[8]) { + for (int i = 0; i <= 0xFFF; ++i) { + double f = (double)i * M_PI / 0x1000; + lut[i] = sin(f) * 0x1000; + } + } + if ((neg = x < 0)) x = -x; + t = lut[x&0xFFF]; + if (x % FX(2) > FX(1)) t = -t; + return neg ? -t : t; +} + +static bool +f_xsin(PezContext *cx, int argc) +{ + + PezNumber n; + TRY(pez_checksig(cx, argc, "xsin", "number")); + pez_getnumber(cx, &n, -1); + return pez_pushnumber(cx, xsin(n)); +} + +static bool +f_xcos(PezContext *cx, int argc) +{ + + PezNumber n; + TRY(pez_checksig(cx, argc, "xcos", "number")); + pez_getnumber(cx, &n, -1); + return pez_pushnumber(cx, xsin(n + 0x800)); +} + static const struct coredef { const char *n; PezCFn *f; } core[] = { { "printf", f_printf }, { "sprintf", f_sprintf }, @@ -2419,6 +2477,10 @@ static const struct coredef { const char *n; PezCFn *f; } core[] = { { "io#read", f_ioread }, { "io#write", f_iowrite }, { "io#close", f_ioclose }, + { "abs", f_abs }, + { "sqrt", f_sqrt }, + { "xsin", f_xsin }, + { "xcos", f_xcos }, }; static bool -- cgit v1.2.3