【发布时间】:2016-04-02 11:49:12
【问题描述】:
下周我有一个即将进行的项目,过去 2 天我一直在研究如何进行 nth root。
我需要在 Assembly NASM 中模拟几何平均值。
我知道 FPU 有关于平方根的指令,但这不会让我走得太远。
目前,我可以输入任意数量的输入,并且可以毫无问题地将它们相乘。但我被“第 n 个根”部分卡住了,因为我不知道如何使用 NASM。
这是我当前的代码:
global _main
extern _printf, _scanf, _system
section .text
_main:
mov ebp, esp; for correct debugging
push clr
call _system
add esp, 4
; start of INITIALIZE
;printf("Enter number of elements")
push print1
call _printf
add esp, 4
; scanf number of elements
push n
push scan1
call _scanf
add esp, 8
; printf("enter n integers")
push dword [n]
push print2
call _printf
add esp, 8
fld qword [n2]
; scan first element
push n2
push scan2
call _scanf
add esp, 8
fld qword [n2]
JE J1
MOV EBX, 1
CMP EBX, [n]
JE J1
L1:
push n2
push scan2
call _scanf
add esp, 8
fld qword [n2]
fmul st1, st0
fstp qword [ans]
INC EBX
CMP EBX, dword [n]
JE J1
LOOP L1
J1:
fst qword [ans]
push dword [ans+4]
push dword [ans]
push print3
call _printf
add esp, 12
mov dword [data8], n
fld qword [data7]
fld qword [data8]
fdiv st1, st0
fstp qword [ans]
fst qword [ans]
push dword [ans+4]
push dword [ans]
push print3
call _printf
add esp, 12
xor eax, eax
ret
section .data
clr db "cls", 0
print1 db "Enter the number of elements:", 13,10,0
scan1 db "%d" , 0
scan2 db "%lf" , 0
n dd 0
n2 dq 0.0
n3 dq 0.0
print2 db "Enter %d values:", 13,10,0
print3 db "Value is %g", 13, 10,0
data8 dq 3.0
ans dq 0.0
loopstart dq 1.0
data7 dq 1.0
或者是否也可以使用外部 C 函数来提取第 n 个根?
编辑:尝试使用 C 中的 _pow。我有这段代码,但它不起作用,有人可以帮忙吗?
LEA ESI, [return]
push ESI
push dword [pushingthing+4]
push dword [pushingthing]
push dword [ans+4]
push dword [ans]
push pow1
call _pow
add esp, 24
section .data
return dq 0.0
pushingthing dq 2.0
pow1 dd "%g, %g", 13, 10, 0
这样做是因为 pow(在 C 中)具有 pow(x,y) 的格式,它们都是双精度并返回双精度值。请检查。
【问题讨论】:
-
当然,知道
n-th root 与1/n的幂相同,您可以使用C 函数pow。在汇编中,您可以使用对数。 -
我仍然不太清楚如何将浮点值推送到具有返回值的 C 函数中。你可以教我吗?我一直在互联网上寻找解决方案,但我很难过。
-
这在您的平台的调用约定中有所描述(您没有提及)。通常你在 cpu 堆栈上传递输入参数,然后在
st(0)中取回结果。 -
我认为调用约定是 ISAx87。我还是不太明白,所以我会尝试另一种解决方案。您在汇编中提到了对数,但我拥有的当前指令集自动设置为 log2。我不是数学天才,所以我真的不知道如何解决这个问题。
-
n-th root = 2^(log2(x) / n)
标签: assembly root nasm exponent