zoukankan      html  css  js  c++  java
  • 快速计算一个数的平方根及其倒数

    源自 http://www.matrix67.com/blog/archives/362

    float Q_rsqrt( float number )
    {
      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

      #ifndef Q3_VM
      #ifdef __linux__
        assert( !isnan(y) ); // bk010122 - FPE?
      #endif
      #endif
      return y;
    }

    /*
    ================
    SquareRootFloat
    ================
    */
    float SquareRootFloat(float number) {
        long i;
        float x, y;
        const float f = 1.5F;

        x = number * 0.5F;
        y  = number;
        i  = * ( long * ) &y;
        i  = 0x5f3759df - ( i >> 1 );
        y  = * ( float * ) &i;
        y  = y * ( f - ( x * y * y ) );
        y  = y * ( f - ( x * y * y ) );
        return number * y;
    }

    应用了牛顿迭代法求根,有一个神秘的0x5f3759df,因为0x5f3759df – (i >> 1)出人意料地接近根号y的倒数!!!

  • 相关阅读:
    7.python常用模块
    7.python3实用编程技巧进阶(二)
    7.Flask文件上传
    7.Django CSRF 中间件
    7.Ajax
    6.python内置函数
    6.python3实用编程技巧进阶(一)
    6.jQuery(实例)
    PhpStorm 10.0.1破解激活步骤
    PyCharm 2018.1破解激活步骤
  • 原文地址:https://www.cnblogs.com/codec/p/4035457.html
Copyright © 2011-2022 走看看