Re: LZ: mathmatical routines


[Prev][Next][Index][Thread]

Re: LZ: mathmatical routines



Will Stokes (3D Diamond productions / Global Games) wrote:
> 
> A few questions. How can I take the square root of numbers in assembler? I
> need a routine but I can't find one anywhere.


Here's a routine I made. It doesn't work 100%, because the answer is
either the truncated square root or the truncated square root+1 (though
not roundet, if the sqrt should be 12.1, the result may still be 12).
One way to avoid this is to check if Sqr(answer) is closer than
Sqr(answer+1).


Sqrt:         ; In: HL - number, Out: A - truncated square root
 ld de,$00FF  ; D is the lower boundary and E is the upper boundary
SQT_Loop:
 push de
 push hl
 ld a,d
 add a,e
 rr a         ; A = (d+e)/2
 adc a,0
 ld b,8       ; Preparing a*a -> hl
 ld d,0
 ld e,a
 ld h,a
 ld l,0
SQT_MulStep:
 add hl,hl
 jr nc,SQT_NoAdd
 add hl,de
SQT_NoAdd:
 djnz SQT_MulStep
 ld b,h
 ld c,l
 pop hl
 ld a,h         ; Comparing BC with HL
 cp b
 jr c,SQT_High
 jr nz,SQT_Low
 ld a,l
 cp c
 jr c,SQT_High
 jr nz,SQT_Low
 pop bc
 ld a,e
 ret
SQT_Low:         ; The SQR was too low, change lower boundary
 ld a,e
 pop de
 inc a
 ld d,a
 cp e
 jr nz,SQT_Loop
 ret
SQT_High:        ; The SQR was too high, change upper boundary
 ld a,e
 pop de
 dec a
 ld e,a
 cp d
 jr nz,SQT_Loop
 ret


> Second. If you want see if something is less then or greater then do you
> use C and NC like Z and NZ right? I.E.,   CALL_C(routine)


Yup. C = the register you compare with was greater than the one stored in A.


> Third, is this an okay wya to take the abs value of a number?


I'm not sure if CP 0 sets the carry flag if the number is negative. A negative
number can also be a positive number. For example, -1 = 65535. I don't know
how the CP instructions works then. I do know that you can check then last
bit though, and if the last bit is set, then the number is negative:


abs:          ; In: A - the value   Out: A - |A|, the absolute value
 ld a,number
 bit 7,a
 ret z
 neg
 ret


<pre>
-- 
Jimmy Mårdell               I just don't care about the whales,
mailto:mja@algonet.se       who cares if the ecosystem fails?
http://www.algonet.se/~mja  We are the crowns of creation,
IRC: Yarin                  we may do whatever we please  - Fuck nature /CRD
</pre>


References: