top of page

6

C/C++ Program for Babylonian method for square root.

program solution

#include <stdio.h>

 

// 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();

}

Output

Square root of 50 is 7.071068

 

Example:

n = 4 /*n itself is used for initial approximation*/

Initialize x = 4, y = 1

Next Approximation x = (x + y)/2 (= 2.500000),

y = n/x (=1.600000)

Next Approximation x = 2.050000,

y = 1.951220

Next Approximation x = 2.000610,

y = 1.999390

Next Approximation x = 2.000000,

y = 2.000000

Terminate as (x - y) > e now.

bottom of page