Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Square Root Computation Function (rootDemo.c) The standard math library provides

ID: 3796402 • Letter: S

Question

Square Root Computation Function (rootDemo.c) The standard math library provides a function to compute the square root value of a number. In this exercise, we’ll be writing our own function to compute the square root value. Given a number n, the square root can be approximated by repeated calculation using the formula,

xi = 1 2 (xi1 + n xi1 ) 5 where x1 = 1.0.

We continue to compute xi until |xi - xi1| where is some small constant value. For the purposes of this exercise you may set = 0.0005. The function should compute the square root of n and return the result. If an error condition should occur (n is negative) the function should display an appropriate error message and quit. Implement this function: double squareRoot(double n); Example: When you run your demo program with n = 5,

the output should look like following

x sqrt(x)

5 2.236069

Explanation / Answer

// C code rootDemo.c
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <math.h>

double squareRoot(double n)
{
   if(n < 0)
   {
       printf("Negative Input ");
       return 0;
   }

   double delta = 0.0005;
   double lastGuess = n/2;
   double nextGuess;

   while(1)
   {
       nextGuess = 0.5*(lastGuess + n/lastGuess);

       if((lastGuess- nextGuess) < delta)
           break;
      
       lastGuess = nextGuess;
      
   }


   return nextGuess;

}

int main()
{
  
   double n ;

   printf("Enter number: ");
   scanf("%lf",&n);

   printf("sqrt(%0.1lf): %lf ",n,squareRoot(n));
   return 0;
}

/*
output:

Enter number: 5
sqrt(5.0): 2.236069


*/

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote