How does this float square root approximation work?

前端 未结 4 996
终归单人心
终归单人心 2020-12-24 01:54

I found a rather strange but working square root approximation for floats; I really don\'t get it. Can someone explain me why this code works?

f         


        
4条回答
  •  礼貌的吻别
    2020-12-24 02:16

    Let y = sqrt(x),

    it follows from the properties of logarithms that log(y) = 0.5 * log(x) (1)

    Interpreting a normal float as an integer gives INT(x) = Ix = L * (log(x) + B - σ) (2)

    where L = 2^N, N the number of bits of the significand, B is the exponent bias, and σ is a free factor to tune the approximation.

    Combining (1) and (2) gives: Iy = 0.5 * (Ix + (L * (B - σ)))

    Which is written in the code as (*(int*)&x >> 1) + 0x1fbb4000;

    Find the σ so that the constant equals 0x1fbb4000 and determine whether it's optimal.

提交回复
热议问题