### newton's method to find square root using recursion

This question is from my book trying to solve but problem in the code could anyone help/ what's wrong in my code ?? Please help
The function sqrt from the header file cmath can be used to find the square root of a nonnegative real number. Using Newtonâ€™s method, you can also write an algorithm to find the square root of a nonnegative real number within a given tolerance as follows: Suppose x is a nonnegative real number, a is the approximate square root of x, and epsilon is the tolerance. Start with a = x.
a. If |a2 - x| <= epsilon, then a is the square root of x within the tolerance; otherwise:
b. Replace a with (a2 + x) / (2a) and repeat Step a
in which |a2 - x| denotes the absolute value of a2 - x.
Write a recursive function to implement this algorithm to find the square root of a nonnegative real number. Also, write a program to test your function.

[code]

#include<iostream>
#include<cmath>

using namespace std;

double root(double x, double e);

int main() {

double x,e;

cout<<"Enter a number : ";
cin>>x;
cout<<"Enter the tolerance: ";
cin>>e;

cout << root(x,e);

return 0;
}

double root(double x, double e) {
double a = x;
if (abs(a*a - x) <= e)
{
return a;
}
else
{
return root((a*a + x) /(2*a),e);
}

}

[code]
Last edited on
In function root(), this looks wrong:
 123 double a = x; if (abs(a-x) <= e) {

since a is assigned the same value as x, abs(a-x) will always be zero, won't it?
It was my typo error actually, I just corrected it, but the program still isn't working. any idea whats wrong
 It was my typo error actually, I just corrected it,
when you say "corrected" perhaps you should say "changed" because it's still wrong. Here you are comparing a2 to x, where a is equal to x.
 123 double a = x; if (abs(a*a - x) <= e) {

I think your function double root(double x, double e) which currently accepts two parameters, will need instead to have three parameters:
1. the original number
2. the estimated square root
3. the required tolerance
Last edited on
Topic archived. No new replies allowed.