Skip to content

Instantly share code, notes, and snippets.

@Lukas0025
Last active August 6, 2021 12:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Lukas0025/f83611f251ca8f6ef996ebf7b638c6f8 to your computer and use it in GitHub Desktop.
Save Lukas0025/f83611f251ca8f6ef996ebf7b638c6f8 to your computer and use it in GitHub Desktop.
Calculate sqrt using newton iteration method
;;
; Calculate sqrt using newton iteration method
; Assembly version of https://gist.github.com/Lukas0025/b6aacb8d2a5d79d51d2f9ca7cd5af2ab with fixed iteration count
; @autor Lukáš Plevač <lukas@plevac.eu>
; @date 6.8.2021
; Under CC0
;
%include "io.inc"
section .data
myx dd 3.0
section .text
global CMAIN
;;
; @param eax number for sqrt
; @return eax = sqrt(eax)
NSQRT:
FINIT
;LOAD X
push eax
FLD dword [esp]
;FLD2
FLD1
FLD1
FADD
; initial estimate
FDIV ; x / 2
; 3 iterations
mov ecx, 3
NSQRT_LOOP:
; x{n} = x{n-1} - (x{n-1} ** 2 - x) / (2 * x{n-1})
FLD st0 ; load x{n-1}
FLD st0 ; load x{n-1}
FMUL ; x{n-1} ** 2
FLD dword [esp] ; load x{0}
FSUB ; - n
; FLD2
FLD1
FLD1
FADD
FLD st2 ; load x{n-1}
FMUL
FDIV
FSUB
; debug
; FST dword [myx]
LOOP NSQRT_LOOP
FSTP dword [esp]
pop eax
ret
CMAIN:
mov ebp, esp; for correct debugging
;write your code here
xor eax, eax
mov eax, [myx]
call NSQRT
ret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment