Skip to content

Instantly share code, notes, and snippets.

@devilholk
Created December 2, 2019 17:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devilholk/bfa3e0d538a3b306ff4ad2ca4386d463 to your computer and use it in GitHub Desktop.
Save devilholk/bfa3e0d538a3b306ff4ad2ca4386d463 to your computer and use it in GitHub Desktop.
Integer sine approximation
#include <stdint.h>
#define table_length_bits 5
//full_table_index_type have to be at least table_length_bits + 2
#define full_table_index_type uint_least8_t
//table_index_type have to be at least table_length_bits
#define table_index_type uint_least8_t
#define storage_bits 15
//Output will be +/- storage_bits so 15 bits storage will be 16 bit output
#define storage_type int16_t
#define index_bits 16
#define index_type uint_least16_t
#define top(n) ((1 << (n)) - 1)
#define inflation_bits (index_bits - table_length_bits)
#define full_inflation_bits (index_bits - table_length_bits - 2)
//fraction_type have to be at least full_inflation_bits
#define fraction_type uint_least16_t
#define quarter_bits (index_bits - 2)
#define ti_top top(table_length_bits)
#define fib_top top(full_inflation_bits)
const storage_type table[1 << table_length_bits] = {0, 1618, 3232, 4837, 6431, 8007, 9564, 11095, 12598, 14069, 15504, 16899, 18250, 19555, 20809, 22010, 23155, 24240, 25263, 26221, 27112, 27933, 28682, 29358, 29959, 30482, 30927, 31293, 31579, 31783, 31906, 31947};
int16_t get_sine(index_type p) {
full_table_index_type fip = p >> full_inflation_bits;
table_index_type sp = fip & ti_top;
uint_least8_t q = p >> quarter_bits;
fraction_type f = (p - (sp << full_inflation_bits)) & fib_top;
storage_type r1, r2;
if ((q & 0x1) == 0) {
r1 = table[sp];
if (sp == ti_top) {
r2 = r1;
} else {
r2 = table[sp + 1];
}
} else {
r2 = table[ti_top - sp];
if (sp == 0) {
r1 = r2;
} else {
r1 = table[ti_top - sp + 1];
}
}
if (q & 0x2) {
return ((r1 - r2) >> full_inflation_bits) * f - r1;
} else {
return ((r2 - r1) >> full_inflation_bits) * f + r1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment