Babylonian method to find square root in C++
Today we will learn the Babylonian method to find the square root using C++.
This method basically originates from the newton-raphson method.
We all know what a square root of a number is and this method is an olden time approach to computing just that.
The method basically follows the below algorithm –
- First, we start off with a random positive value as close to the root as possible
- then we initialize a variable say y=1;
- Then follow the below two steps until when are left with the answer
- find the avg of x & y and get the approx for the root
- and we set y= n/x
If we follow the above steps in a loop we will ultimately end up the square root of the number itself while using the Babylonian method to solve it :
Babylonian method to find square root in C++
Below defined is the function that computes the square root number the number itself as the input –
#include<iostream.h> #include<math.h> #include<stdio.h> using namespace std; int main() { float sqroot(float a) { //right now we start the approximation with a itself float x = a; float y = 1; //value of e should be accurate float e = 0.000001; while (x - y > e) { x = (x + y) / 2; y = a / x; } return x; } int no; cout<<"Enter number to find square root of"; cin>>no; cout<<"Square root using babylonian method is "<<sqroot(no); return 0; }
OUTPUT - Square root using babylonian method is 8.366600
Leave a Reply