【发布时间】:2009-08-28 21:43:43
【问题描述】:
John Carmack 在 Quake III 源代码中有一个特殊的函数,它计算浮点数的平方根,比普通的 (float)(1.0/sqrt(x)) 快 4 倍,包括一个奇怪的 0x5f3759df 常量。请参阅下面的代码。有人可以逐行解释这里到底发生了什么以及为什么它比常规实现快得多吗?
float Q_rsqrt( float number )
{
long i;
float x2, y;
const float threehalfs = 1.5F;
x2 = number * 0.5F;
y = number;
i = * ( long * ) &y;
i = 0x5f3759df - ( i >> 1 );
y = * ( float * ) &i;
y = y * ( threehalfs - ( x2 * y * y ) );
#ifndef Q3_VM
#ifdef __linux__
assert( !isnan(y) );
#endif
#endif
return y;
}
【问题讨论】:
-
这已经被写了无数次了。见:google.com/search?q=0x5f3759df
-
谢谢。这是一个比“如何在 C# 中使正数变为负数?”更有趣的问题
-
在
i = * ( long * ) &y;这一行中,为什么y的地址被当作指向long的指针然后又被取消引用?
标签: algorithm floating-point square-root