Wednesday 8 June 2016

Babylonian method of finding square root : C program

There are many algorithms to find square root of the number !
Here is the probably coolest and very easy method to find square root in C .

What this method actually is , guessing a number , squaring it , if the difference between square of a guess number and original number is acceptable than assigning the guess number as square root and if not updating the guess number .

Algorithm :

  1. Given a number say x.
  2. Guess the square root of the number , say guess=x/2.
  3. Square your guessed number and subtract it from original number.
  4. If the absolute difference is less than the acceptable tolerance , say ACCURACY , then you are done .
  5. Else calculate new guess number .
      guess = (guess + (original /guess))/2 .
  6. Go to step 3.

C Program : Finding Square Root 



#include < stdio.h >
#define ACCURACY 0.001 // tolerance : you can set by yourself according to requirement

int main()
{
    float number,guess,square_root;
    printf("Enter a number to find square root of it:\n");
    scanf("%f",&number);// storing the number
    guess=number/2;// initializing guess number
    while((guess*guess - number) > ACCURACY)//loop runs until the square root is found
    {
        guess = (guess + number/guess )/2;// updating the guess number
    }
    square_root = guess;//assigning the value of guess number to square root.
    printf("square root of %.2f = %.4f",number,square_root);//final answer
} 

Thanking you !


1 comment :

  1. Thanks a lot Sir, this program is much easier to understand according to the concept. Other programs on the internet takes x and y which is hard to understand.

    ReplyDelete