The squareroot of a number N can be approximated by repeated calculation using t
ID: 3856862 • Letter: T
Question
The squareroot 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 C language function that calculates the squareroot of a number using this method. The initial guess will be the starting value of LG. The program will compute a value for NG using the formula given above. The difference between NG and LG is checked to see whether these two guesses are almost identical. If they are, NG is accepted as the squareroot : otherwise, the next guess (NG) becomes the last guess (LG) and the process is repeated (another value is computed for NG, the difference is checked and so on). The loop should be repeated until the difference is less than 0.005. Write a complete C language program to test your squareroot function for the following numbers: 4, 120.5, 36.01, and 0.25 (Use an initial guess of 1.0).Explanation / Answer
Given below is the code for question. Please rate the answer if it helped. Thank you.
#include <stdio.h>
double square_root(double N, double intitalGuess);
int main()
{
double ans, n;
double initialguess = 1.0;
/*calculate square root of 4*/
n = 4;
ans = square_root(n, initialguess);
printf("square_root(%lf) = %lf ", n, ans);
/*calculate square root of 120.5*/
n = 120.5;
ans = square_root(n, initialguess);
printf("square_root(%lf) = %lf ", n, ans);
/*calculate square root of 36.01*/
n = 36.01;
ans = square_root(n, initialguess);
printf("square_root(%lf) = %lf ", n, ans);
/*calculate square root of 0.25*/
n = 0.25;
ans = square_root(n, initialguess);
printf("square_root(%lf) = %lf ", n, ans);
/*accept a number from user*/
printf(" Enter a number: ");
scanf("%lf", &n);
ans = square_root(n, initialguess);
printf("square_root(%lf) = %lf ", n, ans);
}
double square_root(double N, double initialGuess)
{
double NG, LG = initialGuess;
double diff;
while(1)
{
NG = 0.5 * (LG + N / LG);
diff = NG - LG;
if(diff < 0)
diff = -diff;
if(diff < 0.005)
break;
else
{
LG = NG;
}
}
return NG;
}
output
square_root(4.000000) = 2.000000
square_root(120.500000) = 10.977249
square_root(36.010000) = 6.000833
square_root(0.250000) = 0.500000
Enter a number: 9
square_root(9.000000) = 3.000000
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.