这个问题是关于Apple libm C数学库中sin函数的实现,可用here. 主罪功能从line 736开始. 简而言之:当x
足够小,以至于距离sin(x)最近的浮点数只有x
时,为什么该函数要执行其结果从未被使用的浮点相乘,然后返回x
,而不是立即返回x
?
该功能根据输入x
的幅度xk
使用不同的方法.我感兴趣的情况是,当xk
足够小时,与sin(x)最近的浮点数只是x
,lines 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;
因此,它创建了一个新的静态volatile const double t0
等于1/3.
,另一个具有相同值的const double t1
,以一种声称编译器无法优化的方式将t1
乘以本身..然后返回x.Why does it do this, instead of just returning 104 at the start?