Skip to content

Instantly share code, notes, and snippets.

@rshk
Created December 19, 2012 16:54
Show Gist options
  • Save rshk/4338230 to your computer and use it in GitHub Desktop.
Save rshk/4338230 to your computer and use it in GitHub Desktop.
Sine table generation using Python
#!/usr/bin/env python
## Generate sine table
import math
def rescale(X,A,B,C,D,force_float=False):
retval = ((float(X - A) / (B - A)) * (D - C)) + C
if not force_float and all(map(lambda x: type(x) == int, [X,A,B,C,D])):
return int(round(retval))
return retval
SAMPLES = 256
SCALE = 0,255 ## Output scale range
if __name__ == '__main__':
## Angles in degrees for which to calculate sine
angles = [rescale(i,0,SAMPLES,90,360) for i in range(SAMPLES)]
sin_table = [int(round(rescale(s,-1,1,SCALE[0],SCALE[1]))) for s in [
math.sin(math.radians(a)) for a in angles
]]
print sin_table
import math
SAMPLES = 256
OUTMAX = 255
import sys
if len(sys.argv) > 1:
SAMPLES = int(sys.argv[1])
if len(sys.argv) > 2:
OUTMAX = int(sys.argv[2])
angle_range = [9999, -9999]
sine_range = [99, -99]
rescaled_range = [9999, -9999]
for sample in range(SAMPLES):
angle = (sample * 360.0) / SAMPLES
sine = math.sin(math.radians(angle))
rescaled = int(round(((sine + 1) * OUTMAX ) / 2.0))
angle_range[0] = min(angle_range[0], angle)
angle_range[1] = max(angle_range[1], angle)
sine_range[0] = min(sine_range[0], sine)
sine_range[1] = max(sine_range[1], sine)
rescaled_range[0] = min(rescaled_range[0], rescaled)
rescaled_range[1] = max(rescaled_range[1], rescaled)
print "%4d" % sample,
print "%4d" % angle,
print "%7.3f" % sine,
print "%4d" % rescaled,
print "#" * rescaled,
print
print "-"*60
print "Angle range:", angle_range
print "Sine range:", sine_range
print "Rescaled range:",rescaled_range
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment