Imported Upstream version 3.0
[debian/gnuradio] / gnuradio-core / src / lib / general / gen_sine_table.py
1 #!/usr/bin/env python
2 #
3 # Copyright 2004 Free Software Foundation, Inc.
4
5 # This file is part of GNU Radio
6
7 # GNU Radio is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 2, or (at your option)
10 # any later version.
11
12 # GNU Radio is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16
17 # You should have received a copy of the GNU General Public License
18 # along with GNU Radio; see the file COPYING.  If not, write to
19 # the Free Software Foundation, Inc., 51 Franklin Street,
20 # Boston, MA 02110-1301, USA.
21
22
23 import math
24 import sys
25
26 def wrap (x):
27     if x >= 2**31:
28         return x - 2**32
29     return x
30
31 def gen_approx_table (f, nentries, min_x, max_x):
32     """return a list of nentries containing tuples of the form:
33     (m, c, abs_error).  min_x and max_x specify the domain
34     of the table.
35     """
36     r = []
37     incx = float (max_x - min_x) / nentries
38     for i in range (nentries):
39         a = (i * incx) + min_x
40         b = ((i + 1) * incx) + min_x
41         m = (f(b)-f(a))/(b-a)
42         c = (3*a+b)*(f(a)-f(b))/(4*(b-a)) + (f((a+b)/2) + f(a))/2
43         abs_error = c+m*a-f(a)
44         r.append ((m, c, abs_error))
45     return r
46
47 def scaled_sine (x):
48     return math.sin (x * math.pi / 2**31)
49
50 def gen_sine_table ():
51     nbits = 10
52     nentries = 2**nbits
53
54     # min_x = -2**31
55     # max_x =  2**31-1
56     min_x = 0
57     max_x = 2**32-1
58     t = gen_approx_table (scaled_sine, nentries, min_x, max_x)
59
60     max_error = 0
61     for e in t:
62         max_error = max (max_error, abs (e[2]))
63
64     # sys.stdout.write ('static const int WORDBITS = 32;\n')
65     # sys.stdout.write ('static const int NBITS = %d;\n' % (nbits,))
66
67     sys.stdout.write ('  // max_error = %22.15e\n' % (max_error,))
68
69     # sys.stdout.write ('static const double sine_table[%d][2] = {\n'% (nentries,))
70
71     for e in t:
72         sys.stdout.write ('  { %22.15e, %22.15e },\n' % (2 * e[0], e[1]))
73
74     # sys.stdout.write ('};\n')
75                     
76 if __name__ == '__main__':
77     gen_sine_table ()