home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1993 #1 / NN_1993_1.iso / spool / comp / os / os2 / programm / 7361 < prev    next >
Encoding:
Text File  |  1993-01-06  |  1.9 KB  |  71 lines

  1. Xref: sparky comp.os.os2.programmer:7361 comp.graphics:13471 comp.os.msdos.programmer:11834 comp.sys.ibm.pc.programmer:746
  2. Newsgroups: comp.os.os2.programmer,comp.graphics,comp.os.msdos.programmer,comp.sys.ibm.pc.programmer
  3. Path: sparky!uunet!zaphod.mps.ohio-state.edu!swrinde!sdd.hp.com!ux1.cso.uiuc.edu!news.cso.uiuc.edu!uxa.cso.uiuc.edu!jas37876
  4. From: jas37876@uxa.cso.uiuc.edu (John A. Slagel)
  5. Subject: Re: Fixed point sqrt anyone?
  6. References: <1idsq6INNced@flop.ENGR.ORST.EDU> <1993Jan6.093937.7848@canon.co.uk> <eyal.726317041@ise>
  7. Message-ID: <C0G9yw.138@news.cso.uiuc.edu>
  8. Sender: usenet@news.cso.uiuc.edu (Net Noise owner)
  9. Organization: University of Illinois at Urbana
  10. Date: Wed, 6 Jan 1993 20:52:06 GMT
  11. Lines: 58
  12.  
  13.    
  14.      Here is how I do it.  This is in Microsoft C inline assembler.  This
  15.      just keeps iterating till it finds the root within 1 digit.
  16.       If you want more speed, change the '2' to something higher, but that
  17.       will decrease accuracy.  This is fast!
  18.  
  19.  
  20. #include <stdio.h>
  21.  
  22. int int_sqrt( int c )
  23. {
  24.     _asm {
  25.     mov     cx, 1
  26.     mov     bx, c
  27.     jmp     skip_iterate
  28.  
  29. iterate:
  30.     mov     ax, cx
  31.     sub     ax, bx   ; AX = x - y
  32.     cwd
  33.     xor     ax, dx
  34.     sub     ax, dx  ; AX = abs( AX )
  35.     cmp     ax, 2   ; 2 is the allowed error * 2, so we're getting within 1.
  36.     jl      done    ; if abs(x-y) > 2 then goto done
  37. skip_iterate:
  38.     mov     ax, cx
  39.     add     ax, bx
  40.     shr     ax, 1
  41.     mov     cx, ax   ; x = (x+y)/2
  42.     cwd
  43.     mov     ax, c
  44.     idiv    cx
  45.     mov     bx, ax   ; y = c / x
  46.     jmp     iterate
  47.  
  48. done:
  49.     mov     ax, cx
  50.     add     ax, bx
  51.     shr     ax, 1
  52.     mov     c, ax
  53.     }
  54.     return c;
  55. }
  56.  
  57.  
  58. main()
  59. {
  60.     int i=32000, j, k;
  61.     printf( "%d \n", int_sqrt( i ) );
  62.     return 0;
  63. }
  64.  
  65.  
  66. -- 
  67. -----------------------------------------------------------------------------
  68.  John A. Slagel              "My old man used to tell me, before he left this
  69.  j-slagel1@uiuc.edu           shitty world, never chase buses or women- you
  70.  (217) 337-7930               always get left behind." -The Marlboro Man
  71.