isqrt.c 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /* +++Date last modified: 05-Jul-1997 */
  2. #include <string.h>
  3. #include "benchmarks/basicmath/snipmath.h"
  4. #define BITSPERLONG 32
  5. #define TOP2BITS(x) ((x & (3L << (BITSPERLONG-2))) >> (BITSPERLONG-2))
  6. /* usqrt:
  7. ENTRY x: unsigned long
  8. EXIT returns floor(sqrt(x) * pow(2, BITSPERLONG/2))
  9. Since the square root never uses more than half the bits
  10. of the input, we use the other half of the bits to contain
  11. extra bits of precision after the binary point.
  12. EXAMPLE
  13. suppose BITSPERLONG = 32
  14. then usqrt(144) = 786432 = 12 * 65536
  15. usqrt(32) = 370727 = 5.66 * 65536
  16. NOTES
  17. (1) change BITSPERLONG to BITSPERLONG/2 if you do not want
  18. the answer scaled. Indeed, if you want n bits of
  19. precision after the binary point, use BITSPERLONG/2+n.
  20. The code assumes that BITSPERLONG is even.
  21. (2) This is really better off being written in assembly.
  22. The line marked below is really a "arithmetic shift left"
  23. on the double-long value with r in the upper half
  24. and x in the lower half. This operation is typically
  25. expressible in only one or two assembly instructions.
  26. (3) Unrolling this loop is probably not a bad idea.
  27. ALGORITHM
  28. The calculations are the base-two analogue of the square
  29. root algorithm we all learned in grammar school. Since we're
  30. in base 2, there is only one nontrivial trial multiplier.
  31. Notice that absolutely no multiplications or divisions are performed.
  32. This means it'll be fast on a wide range of processors.
  33. */
  34. void usqrt(unsigned long x, struct int_sqrt *q)
  35. {
  36. unsigned long a = 0L; /* accumulator */
  37. unsigned long r = 0L; /* remainder */
  38. unsigned long e = 0L; /* trial product */
  39. int i;
  40. for (i = 0; i < BITSPERLONG; i++) /* NOTE 1 */
  41. {
  42. r = (r << 2) + TOP2BITS(x); x <<= 2; /* NOTE 2 */
  43. a <<= 1;
  44. e = (a << 1) + 1;
  45. if (r >= e)
  46. {
  47. r -= e;
  48. a++;
  49. }
  50. }
  51. memcpy(q, &a, sizeof(long));
  52. }
  53. #ifdef TEST
  54. #include <stdio.h>
  55. #include <stdlib.h>
  56. main(void)
  57. {
  58. int i;
  59. unsigned long l = 0x3fed0169L;
  60. struct int_sqrt q;
  61. for (i = 0; i < 101; ++i)
  62. {
  63. usqrt(i, &q);
  64. printf("sqrt(%3d) = %2d, remainder = %2d\n",
  65. i, q.sqrt, q.frac);
  66. }
  67. usqrt(l, &q);
  68. printf("\nsqrt(%lX) = %X, remainder = %X\n", l, q.sqrt, q.frac);
  69. return 0;
  70. }
  71. #endif /* TEST */