【问题标题】:Sum of sin() results in asm(x87)sin() 的总和结果为 asm(x87)
【发布时间】:2012-11-03 19:40:13
【问题描述】:

我需要计算y(i) = sin(5*i) 的总和,其中i 每次迭代都会增加。我需要在总和大于3之前计算总和,当总和更大时找到i

使用下面的代码,我得到一个无限循环:

int main() {

float Sum=0;
long i=0;
long A=5;
long B=180;
int C=3;

 _asm{
   finit
 m1:
   inc i
   fldpi    ; load PI
   fmul i   ; PI * i 
   fmul A   ; PI * i * 5
   fdiv B   ; PI * i * 5 / 180 (value in degree)
   fsin ; sin(PI * i * 5 / 180)
   fadd Sum ; counter all lopps result
   ficom C  ; check if lower than 3 go to m1 
   jg m1
 }  
}

【问题讨论】:

  • 我有无限循环和总和 =0.0000 我在调试器中看到它

标签: assembly x87


【解决方案1】:

有一些问题。

  1. FMUL 需要浮点参数,但您传递了 long
  2. FICOM 只设置 FPU 标志,你必须将它们移动到 CPU 或使用 FCOMI
  3. JG 正在检查错误标志,您需要检查进位标志。
  4. 您的代码使浮点堆栈失衡。

奖励:由于 5*PI/180 是常数,您可以预先计算。

你可以使用一些这样的代码(调整你的编译器的语法,这是用于 gnu 汇编器的):

.intel_syntax noprefix
.globl main
main:
    sub esp, 16               # allocate space for i, sum and fmt
    mov dword ptr [esp+4], -1 # i
    fild dword ptr [limit]    # limit
    fldz                      # sum
1:
    inc dword ptr [esp+4]     # i += 1
    fild dword ptr [esp+4]    # i
    fmul qword ptr [factor]   # i * factor
    fsin
    faddp                     # add to sum
    fcomi st, st(1)           # check if below limit
    jb 1b
    fstp qword ptr [esp+8]    # store on stack for printf
    fstp st(0)                # remove limit from fpu stack
    mov dword ptr [esp], offset fmt
    call printf
    add esp, 16               # clean up stack
    xor eax, eax              # return value
    ret

.data
factor: .double .08726646259971647884 # 5 * PI / 180
limit: .int 3
fmt: .string "i=%d sum=%g\n"

See in operation.

【讨论】:

  • 尝试将 lll var 设置为 float 但没有帮助。太阳没有增加
  • 我这样做了,但循环仍然不能正常工作 int main() { float Sum=0;诠释我=0;诠释A=5;诠释 B=180;诠释 C=3; _asm{ finit m1:inc i fldpi fimul A fimul i fidiv B fsin fadd Sum fstp Sum fild Sum ficom C fstsw AX sahf jc m1 } }
【解决方案2】:

也许它是题外话,但使用简单的三角恒等式,您可以使用简单的公式计算任意和值而无需任何循环的答案:

i=ceil(acos(cos(t/2)-2*result_sum*sin(t/2))/t-0.5)

其中 t 是您的步距角(5 度),result_sum - 连续正弦所需的累积总和(在您的情况下为 3)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-07
    • 2015-10-09
    • 2014-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多