telegps-v1.0: Provide one log and append to it
[fw/altos] / src / kernel / ao_sqrt.c
1 /*
2  * Copyright © 2011 Keith Packard <keithp@keithp.com>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; version 2 of the License.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program; if not, write to the Free Software Foundation, Inc.,
15  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
16  */
17
18 #ifndef AO_FLIGHT_TEST
19 #include "ao.h"
20 #endif
21
22 /* Adapted from int_sqrt.c in the linux kernel, which is licensed GPLv2 */
23 /**
24  * int_sqrt - rough approximation to sqrt
25  * @x: integer of which to calculate the sqrt
26  *
27  * A very rough approximation to the sqrt() function.
28  */
29
30 uint32_t
31 ao_sqrt(uint32_t op)
32 {
33         uint32_t        res = 0;
34         uint32_t        one = 1UL << (sizeof (one) * 8 - 2);
35
36         while (one > op)
37                 one >>= 2;
38
39         while (one != 0) {
40                 if (op >= res + one) {
41                         op = op - (res + one);
42                         res = res +  2 * one;
43                 }
44                 res /= 2;
45                 one /= 4;
46         }
47         return res;
48 }