If you don't mind slightly different values due to rounding, I can compress that really well for you.
from math import pi, sin
interval=2*pi/1024
sinval=lambda i:int(round(sin(i*interval)*36))+50
Here is code to actually do what you want; it works with
vals = sorted((sinval(i), i) for i in range(1024))
as test data. You would need to switch the order of val
and index
in the for
loop here if you've got indexes in the first column.
ranges, oldval, oldidx = [[0, 0]], 0, 0
for val, index in vals:
if not (val == oldval and index == oldidx + 1):
ranges[-1].append(oldidx)
ranges.append([val, index])
oldval, oldidx = val, index
ranges[-1].append(oldidx)
ranges.pop(0)
ifs = ('if((index >= {1}) and (index <= {2})) return {0};\n'.format(val, start, end)
for val, start, end in ranges)
print ''.join(ifs)
Edit: Whoops, I was missing a line. Fixed. Also, you're multiplier was actually 36 not 35, I must have rounded (14, 86) to (15, 85) in my head.
Edit 2: To show you how to store only a quarter of the table.
from math import pi, sin
full = 1024
half = 512
quarter = 256
mag = 72
offset = 50
interval = 2 * pi / full
def sinval(i):
return int(round(sin(i * interval) * (mag // 2))) + offset
vals = [sinval(i) for i in range(quarter)]
def sintable(i):
if i >= half + quarter:
return 2 * offset - vals[full - i - 1]
elif i >= half:
return 2 * offset - vals[i - half]
elif i >= quarter:
return vals[half - i - 1]
else:
return vals[i]
for i in range(full):
assert -1 <= sinval(i) - sintable(i) <= 1
If you subtract the offset out of the table just make the first two -vals[...]
instead.
Also, the compare at the bottom is fuzzy because I get 72 off-by-one errors for this. This is simply because your values are rounded to integers; they're all places that you're halfway in between two values so there is very little decrease in accuracy.