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

    其实一步也就可以了。

  • 相关阅读:
    bzoj 2002: [Hnoi2010]Bounce 弹飞绵羊
    1691: [Usaco2007 Dec]挑剔的美食家
    CF809E Surprise me!
    「总结」狄利克雷卷积,莫比乌斯反演和杜教筛
    AT3611 Tree MST
    AT2134 Zigzag MST
    CF891C Envy
    【HNOI2018】游戏
    【HNOI2016】树
    【HNOI2016】网络
  • 原文地址:https://www.cnblogs.com/charlesblc/p/6490255.html
Copyright © 2011-2022 走看看