home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!caen!uflorida!gmt
- From: gmt@beach.cis.ufl.edu (Gary McTaggart)
- Newsgroups: comp.graphics
- Subject: RE: fixed-point square root
- Message-ID: <38189@uflorida.cis.ufl.edu>
- Date: 9 Jan 93 17:25:38 GMT
- Sender: news@uflorida.cis.ufl.edu
- Organization: Univ. of Florida CIS Dept.
- Lines: 52
- Nntp-Posting-Host: beach.cis.ufl.edu
-
- murrayk@prism.CS.ORST.EDU (the Dodger) writes:
- >Well? Does anyone know of a quick and dirty way to get a reasonably accurate
- >square root of a fixed point integer number? My numbers are stored in a 16.16
- >bit format. I've heard of a few ways, but I'm open for ideas. I just want to
- >keep on avoiding floating point for ethical reasons. 8^)
-
- I wrote a routine a while back to do an integer square-root using a lookup
- table. This routine (below) could be modified to do a fixed-point sqrt by
- subtracting 16 (for you case of 16.16 fixed point numbers) from the final
- right shift. If you have any problems or suggestions for improvement,
- please mail me.
-
- --Gary McTaggart
-
- PS:
- I chose to use a relatively small sqrt table because accuracy was not
- important. The table could be boosted up to a larger size for more accuracy.
-
- ----------------------------------------------------------------------
-
- #include <math.h>
-
- /* Create a type for a 32 bit unsigned integer. */
- typedef unsigned long UINT32;
-
- /* These hard-coded numbers are here because of a brain-dead compiler which
- would not resolve constant expressions at compile time. */
- #define ONE_SHL_31 2147483648UL
- #define ONE_SHL_30 1073741824UL
-
- UINT32 sqrt_table[256];
-
- void init_sqrt_table(void)
- {
- unsigned long int i;
-
- for (i = 0; i < 256; i++)
- sqrt_table[i] = sqrt((double) ((UINT32)i << 24) );
- }
-
- /* --------------------------INTEGER SQUARE ROOT------------------------*/
- UINT32 int_sqrt(UINT32 in)
- {
- int lsh = 0;
-
- while (!( (in << lsh) & ( (UINT32) ONE_SHL_30 ) ) )
- lsh++;
- if (lsh % 2)
- lsh++;
-
- return (sqrt_table[( (UINT32)in << lsh) >> 24]) >> ((lsh) / 2);
- }
-