Exercise 6.3 Let’s say you are given a number, a, and you want to nd its square
ID: 3734445 • Letter: E
Question
Exercise 6.3 Let’s say you are given a number, a, and you want to nd its square root. One way to do that is to start with a very rough guess about the answer, x0, and then improve the guess using the following formula: x1 = (x0 +a/x0)/2 For example, if we want to nd the square root of 9, and we start with x0 = 6, then x1 = (6+9/6)/2 = 15/4 = 3.75, which is closer. We can repeat the procedure, using x1 to calculate x2, and so on. In this case, x2 = 3.075 and x3 = 3.00091. So that is converging very quickly on the right answer (which is 3). Write a function called SquareRoot that takes a double as a parameter and that returns an approximation of the square root of the parameter, using this algorithm. You may not use the sqrt() function from the math.h libraryAsyourinitialguess, you should use a/2. Yourfunctionshoulditerateuntilitgetstwo consecutiveestimatesthatdierbylessthan0.0001; in other words, until the absolute value of xn xn1 is less than 0.0001. You can use the built-in fabs() function from the math.h library to calculate the absolute value. IN C.
Explanation / Answer
#include<stdio.h>
double squareroot ( double n ) {
double guess = n/2, oldguess=n;
while ( oldguess*oldguess - guess*guess >= 0.001 ) {
oldguess = guess;
guess = ( guess + n/guess ) / 2;
}
return guess;
}
int main() {
double n;
scanf("%lf", &n);
printf("%lf ", squareroot(n));
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.