[Prev][Next][Index][Thread]
Re: A85: More questions
On Mon, 9 Mar 1998, Erik L Gillespie wrote:
> 2) If I had a dollar for every time I put this algorithm up I'd be rich:
> (You want to take the square root of X)
>
> GUESS = X / 2
> DO
> GUESS = (GUESS + X / GUESS) / 2
> WHILE ABS(GUESS * GUESS - X) > 1.0E-9
I tried to implement this in ti basic and it didn't work so I wrote one
that did. In generic code:
Guess=X/2
Range=Guess/2
while abs(Guess^2-X)>Error do
if Guess^2-X >0
Guess=Guess-Range
else
Guess=Guess+Range
end if
Range=Range/2
end while
This works like a binary search but doesn't work too well with integers so
I messed around and came up with a fast sqrt for 8 bit ints. In Z80 asm:
;want to find sqrt of e
;answer will be in d
ld a,3
ld d,1
SqrtLoop:
cp e
ret nc ;if e < a done
inc d
ld b,d
sla b
add b
jr SqrtLoop
I haven't tested it but the algorithm works.
The answer will always be between 1 and 15 or 16 so the worst case isn't
so bad.
>
> If anyone ever decides to make the assembly routine for a square root
> function, I'd like to have it (source code).
You're welcome.
-Humberto
References: