I need this done real quick. Like an hour or so. Its C++ and please use a functi
ID: 3818413 • Letter: I
Question
I need this done real quick. Like an hour or so.
Its C++ and please use a function passed as an argument of another function (function pointers).
Write a function squareRoot that uses the Newton’s method of approximate calcu-lation of the square root of a number x. The Newton’s method guesses the square root in
x
iterations. The first guess is ------. In each iteration the guess is improved using
2
x
guess + -----------
guess
---------------------------- as the next guess.
2
Your main program should prompt the user for the value to find the square root of (x) and how close the final guess should be to the previous guess (for example, 0.001), and pass these values to the squareRoot function. As a third argument of the function squareRoot pass an error processing function, to be called if the other arguments do not pass validation. For example the error processing function can set the wrong arguments to some default values, or ask the user for new values, or do some other appropriate action. Test squareRoot with at least two error processing functions.
Explanation / Answer
#include <iostream>
#include <math.h>
#include <cstdlib>
using namespace std;
/**
* Error Processing Function
*/
void negCheck(int x) {
if (x < 0)
{
cout << "Square root of a negative number doesn't exists" << endl;
exit(1);
}
}
/**
* Finds out the square root of a given number
*
* x is number whose square root should be computed
* g is the initial guess
*/
double newton(double x, double max_error, void (*errFunc) (int))
{
errFunc(x);
double g = 1;
while (true) {
double ng = (x/g + g)/2;
double relative_error = fabs((ng*ng)-x);
if (relative_error <= max_error)
break;
g = ng;
}
return g;
}
void errorProcess() {
}
int main()
{
double x, tolerance;
cout << "Enter the number : ";
cin >> x;
cout << "Enter maximum error tolerance : ";
cin >> tolerance;
cout << "The square root is "<< newton(x, tolerance, &negCheck) << endl;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.