Skip to content

Commit

Permalink
Use lookup tables for trig
Browse files Browse the repository at this point in the history
  • Loading branch information
leonmavr committed Sep 26, 2024
1 parent 189bfc1 commit 0e777d7
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
21 changes: 21 additions & 0 deletions include/xtrig.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#ifndef XTRIG_H
#define XTRIG_H

#include <stdio.h>
#include <math.h>

#define LUT_BIN_SIZE 0.00174533 // in radians
#define HALF_PI (M_PI / 2.0)
#define LUT_SIZE (int)(HALF_PI/ LUT_BIN_SIZE + 1)

/** sine lookup table (LUT) with sampled values from 0 to pi/2 */
extern double sine_lookup[LUT_SIZE];

/** Initialize lookup tables - must be called before xsin or xcos */
void init_lookup_tables();
/** fast sine */
double xsin(double angle);
/** fast cosine */
double xcos(double angle);

#endif // XTRIG_H
32 changes: 32 additions & 0 deletions src/xtrig.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#include "xtrig.h"

double sine_lookup[LUT_SIZE];

void init_lookup_tables() {
for (int i = 0; i < LUT_SIZE; i++)
sine_lookup[i] = sin(i * LUT_BIN_SIZE);
}

/** Get the index of an angle in the LUT */
static int get_lookup_index(double rad) {
return (int) round(rad / LUT_BIN_SIZE);
}

double xsin(double rad) {
// use the period and symmetry to compute based off [0, pi/2]
rad = fmod(rad, 2*M_PI);
if (rad < 0) rad += 2*M_PI;
if (rad < HALF_PI)
return sine_lookup[get_lookup_index(rad)];
else if (rad < M_PI)
return sine_lookup[get_lookup_index(M_PI - rad)];
else if (rad < 3*HALF_PI)
return -sine_lookup[get_lookup_index(rad - M_PI)];
else
return -sine_lookup[get_lookup_index(2*M_PI - rad)];
}

double xcos(double rad) {
return xsin(HALF_PI - rad);
}

0 comments on commit 0e777d7

Please sign in to comment.