The function sqrt from the header file cmath can be used to find the square root
ID: 3927251 • Letter: T
Question
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.
If |a2– x| <= epsilon, then a is the square root of x within the tolerance, otherwise:
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.(C++)
Explanation / Answer
// C++ to determine square root recursively using newton method
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <fstream>
#include <vector>
#include <math.h>
#include <complex.h>
#include <cmath> // std::abs
using namespace std;
// Returns the square root of x.
float squareRoot(float x, float e, float a)
{
// base case
if (abs(a * a - x) <= e)
{
return a;
}
else
{
// updating square root value
a = (a * a + x) / (2 * a);
// recursively calling function with updated a
return 1.0 *(squareRoot(x, e, a));
}
}
int main()
{
int x;
cout << "Enter x: ";
cin >> x;
float e;
cout << "Enter tolerance: ";
cin >> e;
/* e decides the accuracy level*/
cout << "Square root of " << x << " is " << squareRoot(x,e,x) << endl;
return 0;
}
/*
output:
Enter x: 25
Enter tolerance: 0.000001
Square root of 25 is 5
Enter x: 101
Enter tolerance: 0.001
Square root of 101 is 10.0499
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.