The Wayback Machine - https://web.archive.org/web/20240913092000/https://www.geeksforgeeks.org/fast-method-calculate-inverse-square-root-floating-point-number-ieee-754-format/
Open In App

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

Last Updated : 27 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a 32-bit floating point number x stored in IEEE 754 floating point format, find the inverse square root of x, i.e., x-1/2.
A simple solution is to do floating point arithmetic.

Following is an example function. 

C++14




#include <bits/stdc++.h>
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;
}


Java




import java.io.*;
 
class GFG {
 
    static float InverseSquareRoot(float x)
    {
        return 1 / (float)Math.sqrt(x);
    }
 
    public static void main(String[] args)
    {
        System.out.println(InverseSquareRoot(0.5f));
        System.out.println(InverseSquareRoot(3.6f));
        System.out.println(InverseSquareRoot(1.0f));
    }
}
 
// This code is contributed by souravmahato348.


Python3




# Python code for the above approach
from math import ceil, sqrt
 
def InverseSquareRoot(x) :
     
    return 1/sqrt(x)
 
# Driver Code
print(InverseSquareRoot(0.5) )
print(InverseSquareRoot(3.6) )
print(InverseSquareRoot(1.0) )
 
# This code is contributed by code_hunt.


C#




using System;
 
class GFG {
 
    static float InverseSquareRoot(float x)
    {
        return 1 / (float)Math.Sqrt(x);
    }
 
    public static void Main()
    {
        Console.WriteLine(InverseSquareRoot(0.5f));
        Console.WriteLine(InverseSquareRoot(3.6f));
        Console.WriteLine(InverseSquareRoot(1.0f));
    }
}
 
// This code is contributed by subham348.


Javascript




<script>
        // JavaScript code for the above approach
 
     function InverseSquareRoot(x)
    {
        return 1 / Math.sqrt(x);
    }
 
        // Driver Code
        document.write(InverseSquareRoot(0.5) + "<br/>");
        document.write(InverseSquareRoot(3.6) + "<br/>");
        document.write(InverseSquareRoot(1.0) + "<br/>");
         
        // This code is contributed by sanjoy_62.
    </script>


Output

1.41421
0.527046
1

Time Complexity: O(1)
Auxiliary Space: O(1)

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

C++14




#include <bits/stdc++.h>
using namespace std;
 
// This is fairly tricky and complex process. For details,
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;
}


Java




public class Main {
 
    // This is fairly tricky and complex process. For
    // details, see
    static float inverseSquareRoot(float x)
    {
        float xhalf = 0.5f * x;
        int i = Float.floatToIntBits(x);
        i = 0x5f3759d5 - (i >> 1);
        x = Float.intBitsToFloat(i);
        x = x * (1.5f - xhalf * x * x);
        return x;
    }
 
    public static void main(String[] args)
    {
        System.out.println(inverseSquareRoot(0.5f));
        System.out.println(inverseSquareRoot(3.6f));
        System.out.println(inverseSquareRoot(1.0f));
    }
}


Python3




# Python program for the above approach
import struct
 
def inverse_square_root(x):
    # This is fairly tricky and complex process. For
    # details, see
    xhalf = 0.5 * x
    i = struct.unpack('i', struct.pack('f', x))[0]
    i = 0x5f3759d5 - (i >> 1)
    x = struct.unpack('f', struct.pack('i', i))[0]
    x = x * (1.5 - xhalf * x * x)
    return x
 
print(inverse_square_root(0.5))
print(inverse_square_root(3.6))
print(inverse_square_root(1.0))
 
# Contributed by adityashrmadev01


C#




using System;
 
public class MainClass
{
    // This is fairly tricky and complex process. For
    // details, see
    static float inverseSquareRoot(float x)
    {
        float xhalf = 0.5f * x;
        int i = BitConverter.ToInt32(BitConverter.GetBytes(x), 0);
        i = 0x5f3759d5 - (i >> 1);
        x = BitConverter.ToSingle(BitConverter.GetBytes(i), 0);
        x = x * (1.5f - xhalf * x * x);
        return x;
    }
 
    public static void Main(string[] args)
    {
        Console.WriteLine(inverseSquareRoot(0.5f));
        Console.WriteLine(inverseSquareRoot(3.6f));
        Console.WriteLine(inverseSquareRoot(1.0f));
    }
}


Javascript




// This is a fairly tricky and complex process. For details,
function inverseSquareRoot(x) {
    let xhalf = 0.5 * x;
    let i = new Float32Array(1);
    let y = new Int32Array(i.buffer);
    i[0] = x;
    y[0] = 0x5f3759d5 - (y[0] >> 1);
    x = i[0];
    x = x * (1.5 - xhalf * x * x);
    return x;
}
 
console.log(inverseSquareRoot(0.5));
console.log(inverseSquareRoot(3.6));
console.log(inverseSquareRoot(1.0));


Output

1.41386
0.526715
0.998307

Time Complexity: O(1)
Auxiliary Space: O(1)

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

 



Similar Reads

Python | Inverse Fast Fourier Transformation
Inverse Fast Fourier transform (IDFT) is an algorithm to undoes the process of DFT. It is also known as backward Fourier transform. It converts a space or time signal to a signal of the frequency domain. The DFT signal is generated by the distribution of value sequences to different frequency components. Working directly to convert on Fourier trans
2 min read
Check if a number is perfect square without finding square root
Check whether a number is a perfect square or not without finding its square root. Examples: Input: n = 36 Output: Yes Input: n = 12 Output: No Recommended PracticeCheck perfect squareTry It! Method 1:The idea is to run a loop from i = 1 to floor(sqrt(n)) and then check if squaring it makes n. Below is the implementation: C/C++ Code // C++ program
9 min read
Digital Root (repeated digital sum) of square of an integer using Digital root of the given integer
Given an integer N, the task is to find the digital root N2 using the digital root of N. Digital Root of a positive integer is calculated by adding the digits of the integer. If the resultant value is a single digit, then that digit is the digital root. If the resultant value contains two or more digits, those digits are summed and the process is r
6 min read
Check whether the given floating point number is a palindrome
Given a floating-point number N, the task is to check whether it is palindrome or not. Input: N = 123.321 Output: YesInput: N = 122.1 Output: No Approach: First, convert the given floating-point number into a character array.Initialize the low to first index and high to the last index.While low &lt; high: If the character at low is not equal to the
4 min read
Check whether given floating point number is even or odd
Given a floating-point number, check whether it is even or odd. We can check whether a integer is even or odd by dividing its last digit by 2. But in case of floating point number we can't check a given number is even or odd by just dividing its last digit by 2. For example, 100.70 is an odd number but its last digit is divisible by 2. Examples : I
6 min read
Smallest number to multiply to convert floating point to natural
Given a positive floating point number n, the task is to find the smallest integer k, such that when we multiply k with n, we get a natural number.Examples: Input : 30.25 Output : 4 30.25 * 4 = 321, there is no number less than 4 which can convert 30.25 into natural number. Input : 5.5 Output : 2 5.5 * 2 = 11, there is no number less than 2 which c
9 min read
Check if a given string is a valid number (Integer or Floating Point) | SET 1(Basic approach)
Validate if a given string is numeric. Examples: Input : str = "11.5" Output : true Input : str = "abc" Output : false Input : str = "2e10" Output : true Input : 10e5.4 Output : false The following cases need to be handled in the code. Ignore the leading and trailing white spaces.Ignore the '+', '-' and'.' at the start.Ensure that the characters in
11 min read
Check if a given string is a valid number (Integer or Floating Point) in Java
In the article Check if a given string is a valid number, we have discussed general approach to check whether a string is a valid number or not. In Java we can use Wrapper classes parse() methods along with try-catch blocks to check for a number. For integer number Integer class provides a static method parseInt() which will throw NumberFormatExcep
4 min read
Check if a given string is a valid number (Integer or Floating Point) in Java | SET 2 (Regular Expression approach)
In Set 1, we have discussed general approach to check whether a string is a valid number or not. In this post, we will discuss regular expression approach to check for a number. Examples: Input : str = "11.5" Output : true Input : str = "abc" Output : false Input : str = "2e10" Output : true Input : 10e5.4 Output : false Check if a given string is
3 min read
Program to calculate Root Mean Square
Given an array of N numbers. The task is to calculate the Root Mean Square(RMS) of the given numbers. Examples: Input: arr[] = {1, 2, 3, 4, 5} Output: 3.31662 Input: arr[] = {10, 4, 6, 8} Output: 7.34847 Approach: The Root Mean Square value of N numbers x1,x2,x3,.....xn can be given as, RMS method first calculates the square of each number and then
4 min read
Compare two floating-point numbers given in Scientific Notations
Given two strings N and M in the form of a * 10 b. The task is to compare given two floating-point numbers and print the smaller number and if both the numbers are equal then print Equal. 0&lt;|a|&lt;10^9 and -10^9&lt;b&lt;10^9. Example: N and M are two numbers with two parts: a1 is mantissa of N and a2 is mantissa of M.b1 is exponent of N and b2 i
11 min read
Draw a circle without floating point arithmetic
Given a radius of a circle, draw the circle without using floating point arithmetic.Following program uses a simple concept. Let the radius of the circle be r. Consider a square of size (2r+1)*(2r+1) around the circle to be drawn. Now walk through every point inside the square. For every point (x,y), if (x, y) lies inside the circle (or x2+ y2 &lt;
5 min read
Binary Search for Rational Numbers without using floating point arithmetic
A rational is represented as p/qb, for example 2/3. Given a sorted array of rational numbers, how to search an element using Binary Search. Use of floating-point arithmetic is not allowed. Example: Input: arr[] = {1/5, 2/3, 3/2, 13/2} x = 3/2 Output: Found at index 2 We strongly recommend you to minimize your browser and try this yourself first.To
9 min read
Draw a circle without floating point arithmetic
Given a radius of a circle, draw the circle without using floating point arithmetic.The following program uses a simple concept. Let the radius of the circle be r. Consider a square of size (2r+1)*(2r+1) around the circle to be drawn. Now walk through every point inside the square. For every point (x,y), if (x, y) lies inside the circle (or x^2+ y^
6 min read
Program to find GCD of floating point numbers
The greatest common divisor (GCD) of two or more numbers, which are not all zero, is the largest positive number that divides each of the numbers. Example: Input : 0.3, 0.9 Output : 0.3 Input : 0.48, 0.108 Output : 0.012 The simplest approach to solve this problem is :a=1.20 b=22.5 Expressing each of the numbers without decimals as the product of p
4 min read
Why do we check up to the square root of a number to determine if that number is Prime?
Why do we check up to the square root of a number to determine if that number is prime?Prime numbers are natural numbers greater than 1 which are divisible only by 1 and itself. Examples include 2, 3, 5, 7, 11, 13, etc. (1 is neither prime nor composite). Here is the code to check whether a number is prime or not. As, the loop checks for each numbe
3 min read
Square root of a number by Repeated Subtraction method
The Repeated Subtraction method for finding the square root of a number is an interesting approach. It involves repeatedly subtracting consecutive odd numbers from the number until you reach zero or a negative number. The number of times you can subtract is the approximate square root of the original number. Given an integer N, the task is to find
4 min read
Finding Inverse of a Square Matrix using Cayley Hamilton Theorem in MATLAB
Matrix is the set of numbers arranged in rows &amp; columns in order to form a Rectangular array. Here, those numbers are called the entries or elements of that matrix. A Rectangular array of (m*n) numbers in the form of 'm' horizontal lines (rows) &amp; 'n' vertical lines (called columns), is called a matrix of order m by n, which is written as m
4 min read
Find smallest perfect square number A such that N + A is also a perfect square number
Given a positive number N. The task is to find out the smallest perfect square number A such that N + A is also a perfect square number or return -1.Examples: Input: N = 3 Output: 1 Explanation: As 1 + 3 = 4 = 22 Input: N=1 Output: -1 Naive Approach: Traverse M from {1, 2, 3, 4, 5...} and check whether (N + M * M) is a perfect square number or not.
9 min read
Find square root of number upto given precision using binary search
Given a positive number n and precision p, find the square root of number upto p decimal places using binary search. Note : Prerequisite : Binary search Examples: Input : number = 50, precision = 3 Output : 7.071 Input : number = 10, precision = 4 Output : 3.1622 We have discussed how to compute the integral value of square root in Square Root usin
9 min read
Square root of a number without using sqrt() function
Given a number N, the task is to find the square root of N without using sqrt() function. Examples: Input: N = 25 Output: 5 Input: N = 3 Output: 1.73205 Input: N = 2.5 Output: 1.58114 Approach 1: We can consider (?x-?x)2 = 0.Replacing one of the ?x's with y, then the equation becomes (y-?x)2 =&gt; y2 - 2y?x + x = 0=&gt; ?x = (y2 + x) / 2y=&gt; ?x =
14 min read
Min operations to reduce N by multiplying by any number or taking square root
Given a number N, the task is to find the minimum value of N by applying below operations any number of times: Multiply N by any positive integerReplace N with sqrt(N), only if N is a perfect square. Examples: Input: N = 20 Output: 10Explanation: Multiply -&gt; 20 * 5 = 100 sqrt(100) = 10, which is the minimum value obtainable. Input: N = 5184 Outp
4 min read
Find square root of a number using Bit Manipulation
Given a non-negative integer N, the task is to find the square root of N using bitwise operations. If the integer is not the perfect square, return largest integer that is smaller than or equal to square root of N i.e., floor(√N). Examples: Input: N = 36Output: 6Explanation: The square root of 36 is 6. Input: N = 19Output: 4Explanation: The square
7 min read
Count numbers in range [L, R] that are divisible by square root of a number
Given two numbers L and R, the task is to find the count of all numbers in a given range [L, R] that are divisible by the square root of that number. The square root of a number is the value that, when multiplied by itself, gives the original number. Note: Here square root of a number represents the floor division. i.e, sqrt(4) = 2, sqrt(10) = 3, s
9 min read
Square root of a number using log
For a given number find the square root using log function. Number may be int, float or double. Examples: Input : n = 9Output : 3 Input : n = 2.93Output : 1.711724 We can find square root of a number using sqrt() method: C/C++ Code // C++ program to demonstrate finding // square root of a number using sqrt() #include&lt;bits/stdc++.h&gt; int main(v
3 min read
Babylonian method for square root
Algorithm: This method can be derived from (but predates) Newton–Raphson method. 1 Start with an arbitrary positive start value x (the closer to the root, the better). 2 Initialize y = 1. 3. Do following until desired approximation is achieved. a) Get the next approximation for root using average of x and y b) Set y = n/x Implementation: C/C++ Code
9 min read
Long Division Method to find Square root with Examples
Given an integer X which is a perfect square, the task is to find the square root of it by using the long division method. Examples: Input: N = 484 Output: 22 222 = 484 Input: N = 144 Output: 12 122 = 144 Approach: Long division is a very common method to find the square root of a number. The following is the stepwise solution for this method: 1. D
10 min read
Smallest root of the equation x^2 + s(x)*x - n = 0, where s(x) is the sum of digits of root x.
You are given an integer n, find the smallest positive integer root of equation x, or else print -1 if no roots are found.Equation: x^2 + s(x)*x - n = 0where x, n are positive integers, s(x) is the function, equal to the sum of digits of number x in the decimal number system. 1 &lt;= N &lt;= 10^18 Examples: Input: N = 110 Output: 10 Explanation: x
8 min read
Find if there is a pair in root to a leaf path with sum equals to root's data
Given a binary tree, find if there is a pair in root to a leaf path such that sum of values in pair is equal to root's data. For example, in below tree there are no pairs in any root to leaf path with sum equal to root's data. The idea is based on hashing and tree traversal. The idea is similar to method 2 of array pair sum problem. Create an empty
8 min read
Reflection of a point at 180 degree rotation of another point
Given two points coordinates (x1, y1) and (x2, y2)on 2D plane. The task is to find the reflection of (x1, y1) at 180 degree rotation of (x2, y2).Examples: Input : x1 = 0, y1 = 0, x2 = 1, y2 = 1 Output : (2, 2) Input : x1 = 1, y1 = 1, x2 = 2, y2 = 2 Output : (3, 3) Let the reflection point of point (x1, y1) about (x2, y2) be (x', y'). For (x', y') b
4 min read
Article Tags :
Practice Tags :