This is all one question, and I use the gcc. Please be sure about your answer. P
ID: 3585496 • Letter: T
Question
This is all one question, and I use the gcc. Please be sure about your answer.
Problem 2 (4 points) iteration The square root of a number a > 0 can be computed using Newton's Zn+1 = 0.5(Zn + a/Zn), where zo is an initial guess Write a C program that takes as input an initial guess ro, o tolerance tol, and number of iterations, n max and iterates the above scheme until convergence or nmax is reached. The iterations converge when n+1-l tol, your program should also output a message with the value of +nl, e.g Enter positive number, initial guess, tolerance, max number of iterations: 100 1 1e-14 5 Max iterations 5 reached, lx-{n+1) -x_al = 3.3e-02 sqrt (100) 1.0000052895643e+01, number of iterations 5 Note: I may have the number of iterations above off by one Here use "Max iterations %d reached, lx-{n+1) -x-nl %.1e " . = . Store your program in file al_newton.cExplanation / Answer
CODE in C++
#include <iostream>
#include <iomanip>
using namespace std;
template <class Y>
Y sqrt (Y x)
{
double g (1);
while (true) {
double ng = (x/g + g)/2;
if (g == ng)
break;
g = ng;
}
return g;
}
void menu()
{
double x, g;
string a = "";
do {
cout << "Enter a number to get the sqrt of: ";
cin >> x;
g = sqrt(x);
cout << "The result is: " << setprecision(100) << g << endl;
cout << "Result^2 = " << setprecision(100) << g*g << endl;
cout << " Do it again ? <y/n> ";
cin >> a;
cout << endl;
} while (a == "y");
}
int main()
{
menu();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.