Fast inverse square root in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an integers x. Our task is to calculate Fast inverse square root (of a 32-bit floating point number.  

The algorithm to find the inverse square root of the number is of great use in programming, such as vector normalization in video games, in 3D graphics, etc.  


Step 1: The algorithm converts the floating point value to integer. 

Step 2: Operate on the integer value and return approximate value of the inverse square root.

Step 3: Convert the integer value back to floating point using the same method used in step 1.

Step 4: The approximation is made for improving precision using Newton’s method. 

Program to illustrate the working of algorithm: 


Live Demo

using namespace std;

float calcInvSqRoot( float n ) {
   const float threehalfs = 1.5F;
   float y = n;
   long i = * ( long * ) &y;

   i = 0x5f3759df - ( i >> 1 );
   y = * ( float * ) &i;
   y = y * ( threehalfs - ( (n * 0.5F) * y * y ) );
   return y;

int main(){
   int n = 256;
   float invSqRoot = calcInvSqRoot(n);
   cout<<"The inverse square root of the number "<<n<<" is "<<invSqRoot;
   return 0;

Output −

The inverse square root of the number 256 is 0.0623942
Published on 22-Jan-2021 18:00:05