Find root of a number using Newton’s method
There are in built functions in all programming languages to calculate square root of any given number but sometimes in any interview we are asked to write our own method to calcualte it.
In this article, I'll explain how to use Newton's method to find out square root of any given number.
You can read more about Newton's method from here.
Problem
You are given a number N and a tolerance level L, Find out the square root of N which is accuare upto L.
Idea
As per Newton's rule, we can have following equation:
Square root of N = 0.5 * (X + (N / X)), where X is any guess.
- We'll use this formula inside a loop and try to guess X, starting from number from N and we'll update it with each iteration with new guessed root, that way it will move towards correct value.
- We'll check the accuracy with every iteration and if it is less than or equal to tolerance level L We'll break out of the loop and return the value.
Implementation
Here is implementation of this approach.
#include <bits/stdc++.h>
using namespace std;
// Find square root of a number using Newton's method
double NewtonSquareRoot(double n, float l)
{
double root; // required answer
double x = n; // start from x as N
while (1) {
// Calculate more closed x
root = 0.5 * (x + (n / x));
// Check for closeness
if (abs(root - x) < l)
break;
// Update root
x = root;
}
return root;
}
int main()
{
double N;
float L;
cout<<"Enter Number ";
cin>>N;
cout<<"Enter tolerance level ";
cin>>L;
cout << "Square root of given number is "<< NewtonSquareRoot(N, L);
return 0;
}
Enter Number 486
Enter tolerance level 0.0001
Square root of given number is 22.0454