第67部分- Linux x86 64位彙編 FPU之三角函數
一般的三角函數,比如正弦,餘弦和正切等都可以輕松的通過FPU來計算得到。
正弦的指令是fsin,餘弦是fcos.同時獲得正弦值和餘弦值可以使用FSINCOS.
正切和反正切的指令是FPTAN和FPATAN。
FPATAN指令使用兩個隐含的源操作數,計算角值ST1/ST0的反正切值。把值儲存在ST1,然後彈出ST0,值移動到ST0位置。
不過就是在使用三角函數之前,需要把值轉換為弧度。
弧度=(角度*pi)/180
正弦示例
.extern printf ;//調用外部的printf函數
.section .data
fmt: .ascii "result is: %f \n"
degree1:
.float 30.0
val180:
.int 180
.section .bss
.lcomm radian1, 4
.lcomm result1, 8
.lcomm result2, 8
.section .text
.globl _start
_start:
nop
finit;//初始化fpu
flds degree1;//加載角度90
fidivs val180;//除以180,儲存在st0
fldpi;//加載π到st1
fmul %st(1), %st(0) ;//乘以π得到弧度,在st0中。
fsts radian1;//儲存弧度到radian1中
fsin;//求正弦,儲存在st0
fstl result1;//正弦結果儲存到result1中。
movq $fmt,%rdi;//調用printf函數
movq result1,%xmm0
call printf
flds radian1;//加載弧度到st0
fcos;//計算餘弦,
fstl result2;//
movq $fmt,%rdi
movq result2,%xmm0
call printf
movq $60,%rax
syscall
as -g -o trigtest.o trigtest_att.s
ld -o trigtest trigtest.o -lc -I /lib64/ld-linux-x86-64.so.2
正弦餘弦示例
.extern printf ;//調用外部的printf函數
.section .data
fmt: .ascii "result is: %f \n"
degree1:
.float 30.0
val180:
.int 180
.section .bss
.lcomm sinresult, 8
.lcomm cosresult, 8
.section .text
.globl _start
_start:
nop
finit
flds degree1
fidivs val180
fldpi
fmul %st(1), %st(0)
fsincos
fstpl cosresult
movq $fmt,%rdi
movq cosresult,%xmm0
call printf
fstl sinresult
movq $fmt,%rdi
movq sinresult,%xmm0
call printf
movq $60,%rax
syscall
as -g -o sincostest.o sincostest.s
ld -o sincostest sincostest.o -lc -I /lib64/ld-linux-x86-64.so.2