The square root of a number N can be approximated by repeated calculation using
ID: 3759343 • Letter: T
Question
The square root of a number N can be approximated by repeated calculation using the formula NG=0.5(LG+N/LG) where NG stands for next guess and LG stands for last guess. Write a function that calculates the square root of a number using this method.
The initial guss will be the starting value of LG. The program will compute a value for NG using the formula given. The difference between NG and LG is checked to see whether these two guess are almost identical. If they are, NG is accepted as the square root; otherwise, the next guess,NG, becomesthe last guess ,LG, and the process is repeated. The loop should be repeated untill the difference is less than 0.055. Use an initial guess of !.0.
Explanation / Answer
#include<iostream>
using namespace std;
double sqrt(double n) {
double sq;
double lg,ng;
lg=1.0;
while (true) {
ng = 0.5*(lg + n/lg);
if (ng-lg < 0 && ng-lg > -0.055) {
sq = lg;
break;
}
if (ng-lg > 0 && ng-lg < 0.055) {
sq = lg;
break;
}
lg=ng;
}
return sq;
}
int main() {
cout<<sqrt(36);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.