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

Write a program that uses the Babylon Algorithm to compute the square root of x.

ID: 3662438 • Letter: W

Question

Write a program that uses the Babylon Algorithm to compute the square root of x. This algorithm is used to compute the square root of x by repeatedly replacing one estimate with a closer estimate. The new estimate can be calculated as (x + 2/x) / 2, the average of x and 2/x.

Use a tolerance flag and make your variables a member of the double class. static final double TOLERANCE 5e-8; Your output should show each value of x as it moves closer to it's square root. For example, the following iterations may appear when computing the square root of 2: 1.5 1.41667 1.41422 x= 1.41421, x*x=2 Test your program by computing the square root of 2, 9, 100, and 10000.

Explanation / Answer

Implementation:

/*Returns the square root of n. Note that the function */

float squareRoot(float n)

{

  /*We are using n itself as initial approximation

   This can definitely be improved */

  float x = n;

  float y = 1;

  float e = 0.000001; /* e decides the accuracy level*/

  while(x - y > e)

  {

    x = (x + y)/2;

    y = n/x;

  }

  return x;

}

/* Driver program to test above function*/

int main()

{

  int n = 50;

  printf ("Square root of %d is %f", n, squareRoot(n));

  getchar();

}

Example:

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