快速平方根算法 magic number

以下函数用于近似计算 1 / √x
计算结果有一定的误差,在对精度有要求的地方还是老老实实用 1.0 / sqrt(x) 吧

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));  // 1st iteration
//  y = y * (threehalfs - (x2 * y * y));  // 2nd iteration, can be removed
    return y;
}

该方法的运行速度已经比标准库慢了许多
仅仅看看而以

int main()
{

    clock_t start_time=clock(); 
    for (int i=0; i<1000000; ++i) {  
        Q_rsqrt(34); 
    } 

    clock_t end_time=clock();

    std::cout << "Q_rsqrt Running time is: "<<static_cast<double>(end_time-start_time)/CLOCKS_PER_SEC*1000<<"ms"<< std::endl;

    clock_t start_time2=clock(); 
    for (int i=0; i<1000000; ++i) {  
        1.0 / sqrt(34);
    } 

    clock_t end_time2=clock();

    std::cout << "sqrt Running time is: "<<static_cast<double>(end_time2-start_time2)/CLOCKS_PER_SEC*1000<<"ms"<< std::endl;
}

Q_rsqrt Running time is: 19.618ms
1.0 / sqrt(34) Running time is: 3.872ms

你可能感兴趣的:(其它,c++,算法)