我正试图在下面编写C程序的汇编版本。它的意思是取9的平方根。在第三次通过我的循环之前,一切似乎都在运行,然后当推送到堆栈时,我的上限和下限值变为1#IND。我不知道为什么,因为它正好印在标签下面
whileLoop公司
,但第二次直接在标签后打印时,我得到了错误的值
不够准确
,即使这两个标签之间的值没有更改,而且在以前的迭代中效果很好。
下面的屏幕截图显示了它如何在同一迭代中成功打印一次,然后第二次打印失败。
程序集代码:
.586
.MODEL FLAT
.STACK 4096
n=550
.data
PUBLIC _sqrtX
upper REAL4 9.0
accuracy REAL4 0.00001
lower REAL4 1.0
guess REAL4 1.0
multValue REAL4 1.0
num REAL4 9.0
two DWORD 2
.code
_sqrtX PROC
finit ;initialize fpu
whileLoop:
fld upper ;push upper onto stack
fld lower ;push lower onto stack
fsub ;subtract upper-lower
fld accuracy ;push accuracy onto stack
fcom ;compare accuracy with upper-lower
fstsw ax ;copy condition code bits to AX
sahf ;shift condition code bits to flags
jna notAccurateEnough ;jump if accuracy is greater
jmp endnewt ;end algorith, is less than accuracy
notAccurateEnough:
;**************************
;************ Logic to implement: guess = (lower + upper) / 2;
;**************************
fld upper ;push upper onto stack
fld lower ;push lower onto stack
fadd ;(lower + upper)
fidiv two ;divide by 2
fstp guess ;set guess to first stack element. guess = (lower + upper) / 2
;**************************
;**************************
;************ Logic to implement: if((guess * guess) > number)
;**************************
fld guess ;push guess onto stack as first element
fld guess ;push guess onto stack again, it is now first and second element
fmul ;multiply first and second element
fcom num ;compare 9 to product of guess*guess:
fstsw ax ;copy condition code bits to AX
sahf ;shift condition code bits to flags
jna SetLower ;if guess is less than num, call set lower and set lower = guess;
;*** else, guess > num
fld guess ;push guess onto the stack
fstp upper ;set upper equal to top of stack: upper = guess
jmp whileLoop
;**************************
setLower:
fld guess ;push guess onto stack
fstp lower ;store guess in lower
jmp whileLoop
endnewt:
mov eax, 0
ret
_sqrtX ENDP
END
我试图在汇编中编写的C算法:
double sqrtX (double x)
{
const double ACCURACY=0.00001;
double lower, upper, guess;
double number;
number = x;
lower = 1;
upper = number;
while ((upper-lower) > ACCURACY)
{
guess = (lower + upper) / 2;
if((guess * guess) > number)
{
upper = guess;
}
else
{
lower = guess;
}
}
return (lower + upper)/2;
}