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");
}