Skip to content

Instantly share code, notes, and snippets.

@wrl wrl/sine_lut.c
Created Apr 1, 2014

Embed
What would you like to do?
sine lookup table
/**
* lut.c: quadrature-optimized sine lookup table
* written in 2014 by william light <wrl@illest.net>
*
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or
* distribute this software, either in source code form or as a compiled
* binary, for any purpose, commercial or non-commercial, and by any
* means.
*
* In jurisdictions that recognize copyright laws, the author or authors
* of this software dedicate any and all copyright interest in the
* software to the public domain. We make this dedication for the benefit
* of the public at large and to the detriment of our heirs and
* successors. We intend this dedication to be an overt act of
* relinquishment in perpetuity of all present and future rights to this
* software under copyright law.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* For more information, please refer to <http://unlicense.org/>
*/
#include <stdint.h>
#include <math.h>
/* tweak TABLE_BITS if you need a smaller table */
#define TABLE_BITS 8
#define TABLE_SIZE (1 << TABLE_BITS)
float lut[TABLE_SIZE + 1];
void
lut_init(void)
{
int i;
for (i = 0; i < TABLE_SIZE + 1; i++)
lut[i] = sin(M_PI_2 * (i / (float) TABLE_SIZE));
}
float
lut_sinf(uint32_t phase)
{
uint32_t quad_phase;
int table_loc;
float x, y[2];
/* strict aliasing blah blah blah (otherwise gcc will complain if we
* do this by type-punning) */
union {
float f;
uint32_t i;
} out;
/* if we're in the second or fourth quadrant, run the phase backwards */
quad_phase = (phase & 0x40000000) ? ~phase : phase;
/* integer part for table index */
table_loc = (quad_phase & 0x3FFFFFFF) >> (30 - TABLE_BITS);
y[0] = lut[table_loc];
y[1] = lut[table_loc + 1];
/* fractional part for linear interpolation */
x = (quad_phase & ((1 << (30 - TABLE_BITS)) - 1)) / (float) (1 << (30 - TABLE_BITS));
out.f = y[0] + ((y[1] - y[0]) * x);
/* invert the second half of the wave by manually
* setting the float's sign bit */
out.i |= phase & 0x80000000;
return out.f;
}
@trm84

This comment has been minimized.

Copy link

commented Mar 14, 2019

where do you get the actual lookup table from?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.