当前位置:编程学习 > C/C++ >>

C++ 快速平方根算法实例代码

SquareRootFloat 函数计算sqrt 的快速算法,出自Carmack的QUAKE3,比库函数快得多

#include <iostream>
using namespace std;
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 ) );        //迭代1    1/sqrt(number)    
         y    = y * ( f - ( x * y * y ) );        //迭代2    1/sqrt(number)   
         //y    = y * ( f - ( x * y * y ) );        //迭代3    1/sqrt(number),如需要更高的精度请迭代多次   
         return number * y;
}

main()
{
    float b = 9852.0;
    //cout<<SquareRootFloat(b)<<endl;       
    float c = SquareRootFloat(b);       
    float e = c * c ;
    cout<<e<<endl;       
    system("pause");
}
补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,