zoukankan      html  css  js  c++  java
  • 快速求平方根,这个好牛逼

    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;
    }

    其实一步也就可以了。

  • 相关阅读:
    HDU 1022 Train Problem I
    HDU 1702 ACboy needs your help again!
    HDU 1294 Rooted Trees Problem
    HDU 1027 Ignatius and the Princess II
    HDU 3398 String
    HDU 1709 The Balance
    HDU 2152 Fruit
    HDU 1398 Square Coins
    HDU 3571 N-dimensional Sphere
    HDU 2451 Simple Addition Expression
  • 原文地址:https://www.cnblogs.com/charlesblc/p/6490255.html
Copyright © 2011-2022 走看看