🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.os.os2.programmer
Article #3307

Re: Fixed point sqrt anyone?

#3307
From: John A. Slagel
Date: Wed, 06 Jan 1993 20:52
58 lines
1923 bytes
   
     Here is how I do it.  This is in Microsoft C inline assembler.  This
     just keeps iterating till it finds the root within 1 digit.
      If you want more speed, change the '2' to something higher, but that
      will decrease accuracy.  This is fast!


#include <stdio.h>

int int_sqrt( int c )
{
	_asm {
	mov     cx, 1
	mov     bx, c
	jmp     skip_iterate

iterate:
	mov     ax, cx
	sub     ax, bx   ; AX = x - y
	cwd
	xor     ax, dx
	sub     ax, dx  ; AX = abs( AX )
	cmp     ax, 2   ; 2 is the allowed error * 2, so we're getting within 1.
	jl      done    ; if abs(x-y) > 2 then goto done
skip_iterate:
	mov     ax, cx
	add     ax, bx
	shr     ax, 1
	mov     cx, ax   ; x = (x+y)/2
	cwd
	mov     ax, c
	idiv    cx
	mov     bx, ax   ; y = c / x
	jmp     iterate

done:
	mov     ax, cx
	add     ax, bx
	shr     ax, 1
	mov     c, ax
	}
	return c;
}


main()
{
	int i=32000, j, k;
	printf( "%d \n", int_sqrt( i ) );
	return 0;
}


-- 
-----------------------------------------------------------------------------
 John A. Slagel              "My old man used to tell me, before he left this
 j-slagel1@uiuc.edu           shitty world, never chase buses or women- you
 (217) 337-7930               always get left behind." -The Marlboro Man
Technical Details
Message-ID: <C0G9yw.138@news.cso.uiuc.edu>
Path: arc1-ca.pugleaf.net!sparky!uunet!zaphod.mps.ohio-state.edu!swrinde!sdd.hp.com!ux1.cso.uiuc.edu!news.cso.uiuc.edu!uxa.cso.uiuc.edu!jas37876
References: <1idsq6INNced@flop.ENGR.ORST.EDU> <1993Jan6.093937.7848@canon.co.uk> <eyal.726317041@ise>

Show Full Headers
Complete Article Headers
Newsgroups: comp.os.os2.programmer,comp.graphics,comp.os.msdos.programmer,comp.sys.ibm.pc.programmer
Path: arc1-ca.pugleaf.net!sparky!uunet!zaphod.mps.ohio-state.edu!swrinde!sdd.hp.com!ux1.cso.uiuc.edu!news.cso.uiuc.edu!uxa.cso.uiuc.edu!jas37876
From: jas37876@uxa.cso.uiuc.edu (John A. Slagel)
Subject: Re: Fixed point sqrt anyone?
References: <1idsq6INNced@flop.ENGR.ORST.EDU> <1993Jan6.093937.7848@canon.co.uk> <eyal.726317041@ise>
Message-ID: <C0G9yw.138@news.cso.uiuc.edu>
Sender: usenet@news.cso.uiuc.edu (Net Noise owner)
Organization: University of Illinois at Urbana
Date: Wed, 6 Jan 1993 20:52:06 GMT
Lines: 58