|
代码如下,有两个,前者计算2D向量的长度,后者计算3D向量的长度,从《3D游戏编程大师技巧》上抄下来的。
========================================================
int Fast_Distance_2D(int x, int y)
{
// this function computes the distance from 0,0 to x,y with 3.5% error
// first compute the absolute value of x,y
x = abs(x);
y = abs(y);
// compute the minimum of x,y
int mn = MIN(x,y);
// return the distance
return(x+y-(mn>>1)-(mn>>2)+(mn>>4));
} // end Fast_Distance_2D
///////////////////////////////////////////////////////////////////////////////
float Fast_Distance_3D(float fx, float fy, float fz)
{
// this function computes the distance from the origin to x,y,z
int temp; // used for swaping
int x,y,z; // used for algorithm
// make sure values are all positive
x = fabs(fx) * 1024;
y = fabs(fy) * 1024;
z = fabs(fz) * 1024;
// sort values
if (y < x) SWAP(x,y,temp)
if (z < y) SWAP(y,z,temp)
if (y < x) SWAP(x,y,temp)
int dist = (z + 11 * (y >> 5) + (x >> 2) );
// compute distance with 8% error
return((float)(dist >> 10));
} // end Fast_Distance_3D
======================================================
书上说是使用了泰勒级数,但我实在没法推导出来。
函数f(x)=x^1/2是没泰勒级数的,唯一比较近似的是函数f(x)=(1+x)^m的泰勒展开,但x又必须是在(-1,1)内。而一般计平方根都是用牛顿叠代法来逼近。
我数学本来就不咋样,算了半天,都快疯了,哪位前辈能教教我,谢谢! |
|