2 * Copyright (C) 1998,1999 Helmut Dersch <der@fh-furtwangen.de>
3 * Copyright (C) 2007 Florian octo Forster <octo at verplant.org>
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the Free
7 * Software Foundation; either version 2 of the License, or (at your option)
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc., 51
17 * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 #include "utils_math.h"
26 // Lookup Tables for Trig-functions and interpolator
28 #define ATAN_TABLE_SIZE 4096
29 #define SQRT_TABLE_SIZE 4096
31 static int *atan_table = NULL;
32 static int *sqrt_table = NULL;
34 static int setup_sqrt_table (void)
39 sqrt_table = (int *) malloc (SQRT_TABLE_SIZE * sizeof (int));
40 if (sqrt_table == NULL)
43 /* Calculate the table entries. */
44 for (i = 0; i < SQRT_TABLE_SIZE; i++)
46 z = ((double) i) / ((double) (SQRT_TABLE_SIZE - 1));
47 sqrt_table[i] = (int) (sqrt( 1.0 + z*z ) * 4096.0 + .5);
51 } /* int setup_sqrt_table */
55 * 256 * sqrt(x1^2 + x2^2)
58 int utils_sqrt2 (int x1, int x2)
62 if (sqrt_table == NULL)
63 if (setup_sqrt_table () != 0)
66 if ((x1 == 0) && (x2 == 0))
72 ret = x1 * sqrt_table[(SQRT_TABLE_SIZE - 1) * x2 / x1] / 16;
76 ret = x2 * sqrt_table[(SQRT_TABLE_SIZE - 1) * x1 / x2] / 16;
80 } /* int utils_sqrt2 */
82 static int setup_atan_table (void)
87 atan_table = (int *) malloc (ATAN_TABLE_SIZE * sizeof (int));
88 if (atan_table == NULL)
91 for (i = 0; i < (ATAN_TABLE_SIZE - 1); i++)
93 z = ((double) i) / ((double) (ATAN_TABLE_SIZE - 1));
94 atan_table[i] = atan ( z / (1.0 - z ) ) * ATAN_TABLE_SIZE * 256;
96 atan_table[ATAN_TABLE_SIZE - 1] = M_PI_4 * ATAN_TABLE_SIZE * 256;
99 } /* int setup_atan_table */
101 int utils_atan2 (int y, int x)
103 if (atan_table == NULL)
104 if (setup_atan_table () != 0)
107 // return atan2(y,x) * 256*ATAN_TABLE_SIZE;
112 return atan_table[(int)( ATAN_TABLE_SIZE * y / ( x + y ))];
116 return -atan_table[ (int)(ATAN_TABLE_SIZE * (-y) / ( x - y ))];
123 return (int)(256*ATAN_TABLE_SIZE * M_PI_2);
125 return -(int)(256*ATAN_TABLE_SIZE * M_PI_2);
130 return atan_table[(int)( ATAN_TABLE_SIZE * y / ( x + y ))] - (int)(M_PI*256*ATAN_TABLE_SIZE);
134 return -atan_table[ (int)(ATAN_TABLE_SIZE * (-y) / ( x - y ))] + (int)(M_PI*256*ATAN_TABLE_SIZE);
140 * vim: set tabstop=8 softtabstop=2 shiftwidth=2 :