[算法笔记]——快速倒数平方根算法

今天刷微信订阅号的时候看到了这个算法,简直惊了
Mark一下
John Carmack’s sqrt [C/C++]

    {
        long i;
        float x2, y;
        const float threehalfs = 1.5F;

        x2 = number * 0.5F;
        y = number;
        i = *(long *)&y; // evil floating point bit level hacking 
        i = 0x5f3759df - (i >> 1); // what the fuck? 
        y = *(float *)&i;
        y = y * (threehalfs - (x2 * y * y)); // 1st iteration 
                                             // y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed 
        return y;
    }

第二次牛顿插值可以忽略
真的神算法
另一种写法

float  sqrt2(const float x)
    {
        const float xhalf = 0.5f*x;

        union // get bits for floating value
        {
            float x;
            int i;
        } u;
        u.x = x;
        u.i = SQRT_MAGIC_F - (u.i >> 1);  // gives initial guess y0
        return x*u.x*(1.5f - xhalf*u.x*u.x);// Newton step, repeating increases accuracy 
    }

附上另几种sqrt()

float sqrt3(const float x)
    {
        union
        {
            int i;
            float x;
        } u;

        u.x = x;
        u.i = (1 << 29) + (u.i >> 1) - (1 << 22);
        return u.x;
    }

(¯﹃¯)


``float sqrt4(const float m)
{
   int i=0; 
   while( (i*i) <= m )
          i++;
    i--; 
   float d = m - i*i; 
 float p=d/(2*i); 
 float a=i+p; 
   return a-(p*p)/(2*a);
}  

“`只列了几种,都引自https://www.codeproject.com/Articles/69941/Best-Square-Root-Method-Algorithm-Function-Precisi
有兴趣的看看哇

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值