
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 Articles
- Square and Square root in Arduino
- C++ Program to count square root cube root and both in given range
- Check if a number is perfect square without finding square root in C++
- What is square root and cube root?
- Guess Nearest Square Root in Python
- 8086 program to find the square root of a perfect square root number
- C++ Range Sum Queries and Update with Square Root
- Find Square Root under Modulo p (Shanks Tonelli algorithm) in C++
- What Is the Square Root?
- Replace Odd Numbers with Square root & Even Numbers with Square in Java
- Finding inverse of a square matrix using SciPy library
- The Inverse Square Law of Illuminance (Laws of Illumination)
- Square root function without using Math.sqrt() in JavaScript
- How to solve square root in division method?
- Find the square root of 2025.

Advertisements