# 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 <iostream> ` `#include <cmath> ` `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; ` `}` |

*chevron_right*

*filter_none*

Output:

1.41421 0.527046 1

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

`#include <iostream> ` `using` `namespace` `std; ` ` ` `// This is fairly tricky and complex process. For details, see ` `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; ` `}` |

*chevron_right*

*filter_none*

Output:

1.41386 0.526715 0.998307

**Source:**

http://en.wikipedia.org/wiki/Fast_inverse_square_root

This article is contributed by **Shalki Agarwal**. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

## Recommended Posts:

- Write a program to calculate pow(x,n)
- Write a program to reverse digits of a number
- Write an Efficient Method to Check if a Number is Multiple of 3
- Write an Efficient C Program to Reverse Bits of a Number
- Minimum number of jumps to reach end
- Babylonian method for square root
- Find minimum number to be divided to make a number a perfect square
- Find whether a given number is a power of 4 or not
- Print all combinations of points that can compose a given number
- Check if a number is multiple of 5 without using / and % operators
- Check whether a given point lies inside a triangle or not
- Magic Square
- Given a number, find the next smallest palindrome
- Count the number of possible triangles
- Select a random number from stream, with O(1) space