# Fast method to calculate inverse square root of a floating point number in IEEE 754 format

Given a 32 bit floating point number x stored in IEEE 754 floating point format, find inverse square root of x, i.e., x-1/2.

A simple solution is to do floating point arithmetic. Following is example function.

 `#include ` `#include ` `using` `namespace` `std; ` ` `  `float` `InverseSquareRoot(``float` `x) ` `{ ` `    ``return` `1/``sqrt``(x); ` `} ` ` `  `int` `main() ` `{ ` `    ``cout << InverseSquareRoot(0.5) << endl; ` `    ``cout << InverseSquareRoot(3.6) << endl; ` `    ``cout << InverseSquareRoot(1.0) << endl; ` `    ``return` `0; ` `}`

Output:

```1.41421
0.527046
1```

Following is a fast and interesting method based for the same. See this for detailed explanation.

 `#include ` `using` `namespace` `std; ` ` `  `// This is fairly tricky and complex process. For details, see  ` `// http://en.wikipedia.org/wiki/Fast_inverse_square_root ` `float` `InverseSquareRoot(``float` `x) ` `{ ` `    ``float` `xhalf = 0.5f*x; ` `    ``int` `i = *(``int``*)&x; ` `    ``i = 0x5f3759d5 - (i >> 1); ` `    ``x = *(``float``*)&i; ` `    ``x = x*(1.5f - xhalf*x*x); ` `    ``return` `x; ` `} ` ` `  `int` `main() ` `{ ` `    ``cout << InverseSquareRoot(0.5) << endl; ` `    ``cout << InverseSquareRoot(3.6) << endl; ` `    ``cout << InverseSquareRoot(1.0) << endl; ` `    ``return` `0; ` `}`

Output:

```1.41386
0.526715
0.998307```

My Personal Notes arrow_drop_up

Article Tags :
Practice Tags :

Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.