- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Fast inverse square root in C++
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.
Algorithm:
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:
Example
#include<iostream> 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
Advertisements
To Continue Learning Please Login
Login with Google