
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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
- Related Questions & Answers
- Square and Square root in Arduino
- 8086 program to find the square root of a perfect square root number
- C++ Program to count square root cube root and both in given range
- Guess Nearest Square Root in Python
- Check if a number is perfect square without finding square root in C++
- C++ Range Sum Queries and Update with Square Root
- Babylonian method to find the square root
- Find Square Root under Modulo p (Shanks Tonelli algorithm) in C++
- Square root function without using Math.sqrt() in JavaScript
- Finding inverse of a square matrix using SciPy library
- The Inverse Square Law of Illuminance (Laws of Illumination)
- Find square root of number upto given precision using binary search in C++
- 8085 program to find square root of a number
- 8086 program to find Square Root of a number
- How to get the square root of 2 in JavaScript?
Advertisements