Babylonian method to find the square root


The Babylonian method to find square root is based on one of the numerical method, which is based on the Newton- Raphson method for solving non-linear equations.

The idea is simple, starting from an arbitrary value of x, and y as 1, we can simply get next approximation of root by finding the average of x and y. Then the y value will be updated with  number / x.

Input and Output

Input:
A number: 65
Output:
The square root of 65 is: 8.06226

Algorithm

sqRoot(number)

Input: The number in real.

Output: Square root of given number.

Begin
   x := number
   y := 1
   precision := 0.000001
   while relative error of x and y > precision, do
      x := (x+y) / 2
      y := number / x
   done
   return x
End

Example

#include<iostream>
#include<cmath>
using namespace std;

float sqRoot(float number) {
   float x = number, y = 1;              //initial guess as number and 1
   float precision = 0.000001;           //the result is correct upto 0.000001

   while(abs(x - y)/abs(x) > precision) {
      x = (x + y)/2;
      y = number/x;
   }
   return x;
}

int main() {
   int n;
   cout << "Enter Number to find square root: "; cin >> n;
   cout << "The square root of " << n <<" is: " << sqRoot(n);
}

Output

Enter Number to find square root: 65
The square root of 65 is: 8.06226


Updated on: 17-Jun-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements