Skip to content

Instantly share code, notes, and snippets.

@Arachnid
Created April 10, 2012 04:45
Show Gist options
  • Save Arachnid/2348362 to your computer and use it in GitHub Desktop.
Save Arachnid/2348362 to your computer and use it in GitHub Desktop.
import math
sintable = [int(math.sin(x*math.pi/512)*32768+32768) for x in range(256)]
def fp_sin(a):
"""Fixed point sine. Input range is [0-2^16), output range likewise."""
a = a & 0xffff
quadrant = a >> 14
index = (a >> 6) & 0xff
if quadrant == 1 or quadrant == 3:
index = 255 - index
value = sintable[index]
if quadrant == 2 or quadrant == 3:
value = 65535 - value
return value
# >>> sum(abs(math.sin(x*math.pi/5000) - table_sin(x*math.pi/5000, fp_sin)) for x in range(10000))
# 19.536966968379307
def fp_sin_lin(a):
"""Fixed point sine. Input range is [0-2^16), output range likewise."""
a = a & 0xffff
quadrant = a >> 14
index = (a >> 6) & 0xff
remainder = a & 0x3f
if quadrant == 1 or quadrant == 3:
index = 255 - index
value = sintable[index]
if index < 255:
value += ((sintable[index + 1] - value) * remainder) >> 6
if quadrant == 2 or quadrant == 3:
value = 65535 - value
return value
# >>> sum(abs(math.sin(x*math.pi/5000) - table_sin(x*math.pi/5000, fp_sin_lin)) for x in range(10000))
# 9.992061405676871
def fp_sin_cos(a):
"""Fixed point sine. Input range is [0-2^16), output range likewise."""
a = a & 0xffff
quadrant = a >> 14
index = (a >> 6) & 0xff
remainder = a & 0x3f
if quadrant == 1 or quadrant == 3:
index = 255 - index
value = sintable[index]
value += (sintable[255 - index] * remainder) >> 16
if quadrant == 2 or quadrant == 3:
value = 65535 - value
return value
# >>> sum(abs(math.sin(x*math.pi/5000) - table_sin(x*math.pi/5000, fp_sin_cos)) for x in range(10000))
# 14.54198779195309
def table_sin(a, fun):
"""Implements sine using fp_sin, without interpolation"""
idx = int(a / math.pi * 32768)
return fun(idx) / 32768.0 - 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment