快速求平方根,这个好牛逼

http://blog.csdn.net/yutianzuijin/article/details/40268445

首先是常规解法,二分法:

float SqrtByBisection(float n)
{
    float low,up,mid,last; 
    low=0,up=(n<1?1:n); 
    mid=(low+up)/2; 
    do
    {
        if(mid*mid>n)
            up=mid; 
        else 
            low=mid;
        last=mid;
        mid=(up+low)/2; 
    }while(fabsf(mid-last) > eps);

    return mid; 
}

 

然后是牛顿迭代法。

好巧妙呀

float SqrtByNewton(float x)
{
    float val=x;//初始值
    float last;
    do
    {
        last = val;
        val =(val + x/val) / 2;
    }while(fabsf(val-last) > eps);
    return val;
}

 

注意,初值选择很重要

float SqrtByNewton(float x)
{
    int temp = (((*(int *)&x)&0xff7fffff)>>1)+(64<<23);
    float val=*(float*)&temp;
    float last;
    do
    {
        last = val;
        val =(val + x/val) / 2;
    }while(fabsf(val-last) > eps);
    return val;
}

 

一步到位,不需要迭代的,牛逼的卡马克算法。是在一段游戏代码里面的。

float SqrtByCarmack( float number )
{
    int i;
    float x2, y;
    const float threehalfs = 1.5F;

    x2 = number * 0.5F;
    y  = number;
    i  = * ( int * ) &y;     
    i  = 0x5f375a86 - ( i >> 1 ); 
    y  = * ( float * ) &i;
    y  = y * ( threehalfs - ( x2 * y * y ) ); 
y  = y * ( threehalfs - ( x2 * y * y ) );      
y  = y * ( threehalfs - ( x2 * y * y ) ); 
    return number*y;
}

其实一步也就可以了。

 

posted @ 2017-03-02 14:00  blcblc  阅读(396)  评论(0)    收藏  举报