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

    其实一步也就可以了。

  • 相关阅读:
    2-jenkins持续集成体系介绍
    第六天打卡
    第五天打卡(find用法)
    第五天打卡
    第四天打卡
    第三天打卡
    第一天:定个小目标,学习REDHAT,希望能去考下RHCE
    day12
    Python3的List操作和方法
    Python3字符串的操作
  • 原文地址:https://www.cnblogs.com/charlesblc/p/6490255.html
Copyright © 2011-2022 走看看