Skip to content

Free games for graphing calculators: NumWorks, TI-Nspire CX, Casio fx-CG50 and soon TI-84 Plus CE. Balatro, Celeste, Hollow Knight, Minecraft and more.

1.8 KB
Raw Blame
/* Checks gen.c's MathHelper sin emulation against the exact table; with an argument, writes a new
 * correction table (to paste into gen.c, replacing SIN_CORR and SIN_EXC). */
#include "../../src/gen.c"
#include <stdio.h>
#include <math.h>
static float ex(unsigned i) { return (float)sin((double)i * 3.141592653589793 * 2.0 / 65536.0); }
int main(int argc, char **argv) {
    int cnt[8] = {0}, big = 0; static unsigned exc[64][2];
    unsigned char tab[4097]; memset(tab, 0, sizeof tab);
    for (unsigned r = 0; r <= 16384; r++) {
        float e = ex(r), p = sin_quadrant(r);
        u32 be, bp; memcpy(&be, &e, 4); memcpy(&bp, &p, 4);
        int d = (int)be - (int)bp;
        if (d < -1 || d > 1) { exc[big][0] = r; exc[big][1] = be; big++; tab[r >> 2] |= (unsigned char)(3 << ((r & 3) * 2)); continue; }
        cnt[d + 2]++;
        tab[r >> 2] |= (unsigned char)(((d + 1) & 3) << ((r & 3) * 2));
    }
    printf("big %d, corrections -1:%d 0:%d +1:%d\n", big, cnt[1], cnt[2], cnt[3]);
    if (argc > 1) {
        FILE *f = fopen(argv[1], "w");
        fprintf(f, "/* MathHelper sin table corrections (generated by tests/gen/t_sintab2.c): 2 bits per\n * first-quadrant index, value = correction in ulps + 1, 3 = see SIN_EXC */\nstatic const uint8_t SIN_CORR[4097] = {\n");
        for (int i = 0; i < 4097; i++) fprintf(f, "%u,%s", tab[i], (i % 24 == 23) ? "\n" : "");
        fprintf(f, "};\n/* entries whose correction is beyond one ulp: index, exact float bits */\nstatic const u32 SIN_EXC[][2] = {");
        for (int i = 0; i < big; i++) fprintf(f, "{%u, 0x%08xu},", exc[i][0], exc[i][1]);
        fprintf(f, "{65536, 0}};\n");
        fclose(f);
    }
    /* verify full table */
    int bad = 0;
    for (unsigned i = 0; i < 65536; i++) if (sin_index(i) != ex(i)) bad++;
    printf("full-table mismatches with current corrections: %d\n", bad);
    return 0;
}