Help with recursive square root

Hello,

I am trying to write this recursive function for my class. We are to use Newton's method to find the square root of a nonnegative real number.

Here is the meat of the question.

If the absolute value of a^2-x <= epsilon, then a is the square root of x within the tolerance;
otherwise:
Replace a with (a^2+x)/(2a) and repeat step a where the abs(a^2 - x) denotes the absolute value of a^2-x




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <cmath>
#include <iomanip>

using namespace std;

double squareRoot(double num, double a, double episoln);

int main()
{
	double number;
	double episoln = 0.001;

	cout<<fixed<<showpoint<<endl;
	cout<<setprecision(2);

	cout<<"Enter a positive number: "<<flush;
	cin>>number;
	cout<<endl;

	cout<<"Square root of "<<number<<" = "
		<<squareRoot(number, number, episoln);

	cout<<endl;
	return 0;
}

double squareRoot(double num, double a, double episoln)
{
	// WRITE YOUR CODE HERE
	

	if ((abs(pow(num, 2)) - a) <= episoln)
	{
		return a;
	}
	else
	{
		return squareRoot(abs(pow(num, 2) + num / (2 * a)), num , episoln);
	}
}
Last edited on
Topic archived. No new replies allowed.