Python实现平方根倒数速算法

0x5f3759df
python代码如下:

class Solution():
    def mySqrt(self,num):
        t = num
        t = 0x5f3759df - (t >> 1)
        while not (t * t <= num and (t+1) * (t+1) > num):
            t = (num / t + t) / 2
        return t

C代码如下:

float InvSqrt(float x)
      {
      float xhalf = 0.5f*x;
      int i = *(int*)&x; // get bits for floating value
      i = 0x5f3759df - (i>>1); // gives initial guess y0
      x = *(float*)&i; // convert bits back to float
      x = x*(1.5f-xhalf*x*x); // Newton step, repeating increases accuracy 
      return x;
      }

CHRIS LOMONT
论文地址:http://www.matrix67.com/data/InvSqrt.pdf

你可能感兴趣的:(Python)