小言_互联网的博客

sqrt算法的实现

338人阅读  评论(0)

sqrt()算法的实现:牛顿迭代法,求a的平方根

Xn+1=(Xn+a/Xn)/2;

还有一种方法,直接暴力得到最接近平方根的数,不用那么多习迭代。

float InvSqrt(float x)
{
    float xhalf = 0.5f*x;
    int i = *(int*)&x; // get bits for floating VALUE 
    i = 0x5f375a86- (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
    x = x*(1.5f-xhalf*x*x); // Newton step, repeating increases accuracy
    x = x*(1.5f-xhalf*x*x); // Newton step, repeating increases accuracy

    return 1/x;
}

 


转载:https://blog.csdn.net/qq_39326472/article/details/88319812
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场