Apple libm 的 sin 函数

问题描述 投票:0回答:1

这个问题是关于 Apple 的 libm C 数学库中 sin 函数的实现,可以在这里找到。主要的 sin 函数从第 736 行开始。简而言之:当 x 足够小,以至于最接近 sin(x) 的浮点数只是

x
时,为什么该函数执行浮点乘法,其结果从未被使用,然后返回
x
,而不是仅仅返回
x
立即?
该函数根据输入 

xk

的大小

x
使用不同的方法。我感兴趣的情况是当
xk
足够小,以至于最接近 sin(x) 的浮点数就是
x
第 809-829 行
。我猜想在这种情况下该函数会刚刚完成return x。它的作用如下:
/*  Make t0 volatile to force compiler to fetch it at run-time
    rather than optimizing away the multiplication.
*/
static volatile const double t0 = 1/3.;

/*  Get t0 once.  If we wrote "t0*t0", the compiler would load it
    twice, since it is volatile.
*/
const double t1 = t0;

/*  Perform a multiplication and pass it into an assembly construct to
    prevent the compiler from knowing we do not use the result and
    optimizing away the multiplication.
*/
__asm__("" : : "X" (t1*t1));

// Return the floating-point number nearest sine(x), which is x.
return x;

因此它创建了一个新的 static 易失性 const double 
t0

等于

1/3.
,另一个具有相同值的 const double
t1
,以一种声称编译器无法优化的方式将
t1
自身相乘。 .然后返回x。
为什么要这样做,而不是一开始就返回 
x

    

c trigonometry libm
1个回答
0
投票
...为什么该函数执行浮点乘法,其结果从未被使用然后返回
x

...


浮点乘法运算有两个输出。一个是浮点寄存器中的数值,另一个是浮点状态位中的更新标志。在您询问的代码中,
x

非常小,以至于最接近 sin

x
的可表示值是
x
,因此它将是函数的返回值。然而,
x
的正弦并不完全是
x
,所以我们想举起不精确的标志。将
1/3.
本身相乘即可实现这一点。
    

© www.soinside.com 2019 - 2024. All rights reserved.