...

/

Discussion: Forget the sqrt() Function

Discussion: Forget the sqrt() Function

Execute the code to understand the output and gain insights into iterative approximation.

Run the code

Now, it's time to execute the code and observe the output.

#include <stdio.h>

double babylonian(double r)
{
  double low, high;
  int x;
  const int precision = 7;
  low = 1.0;
  high = r;
  for( x=0; x<precision; x++ ) {
    high = (high+low)/2.0;
    low = r/high;
  }
  return(low);
}

  int main()
{
  double pv, sr;
  printf("Enter a positive value: ");
  scanf("%lf", &pv);
  if( pv <= 0 )
    return(1);
  sr = babylonian(pv);
  printf("The result is %f\n", sr);
  return(0);
}
C code for the given puzzle

Understanding the output

The code uses the Babylonian method to calculate a square root:

Enter a positive value: 7
The result is 2.645751
Code output

The square root of seven is 2.645751 (plus change).

Most people learn how to perform long division but quickly forget how to calculate a square root. Even if you remember the way you were taught, many other techniques exist to ...