-3

Can someone explain the following code? what is the use of the variable ort?

void squart_root(double a)
{
if (a>0.0){
    double root = 1, ort = 0;
    while(ort!=root)
    {
        ort = root;
        root = ((a/root) + root) / 2;
    }
    printf("Root is : %lf",root);
}else if(a==0.00000){
    printf("Root is : %lf",a);
}else{
    printf("Cannot find the square root of a negative number");
    }
}
  • Looks like it calculates the square root of a number. What exactly are you having trouble with? – paddy Nov 08 '13 at 03:13
  • 2
    http://en.wikipedia.org/wiki/Methods_of_computing_square_roots, first "big" equation, better explained further down. The `while` goes on with the sequence until the computation exceeds the precision of `double`. – Matteo Italia Nov 08 '13 at 03:14
  • yes I can understand that. I need what is the algorithm and how it executed line by line? – user2967429 Nov 08 '13 at 03:17
  • 1
    What's so difficult? At each iteration `ort` is `x_n`, while `root` is `x_{n+1}`; the `while` stops when `x_n==x_{n+1}`, i.e. when we reached a point in the sequence where the precision of the `double` data type doesn't admit to go further in the sequence. – Matteo Italia Nov 08 '13 at 03:19
  • Use a debugger. Step through it line by line. – nhgrif Nov 08 '13 at 03:22
  • This is a numerical method for finding square root of numbers. I am not sure but I think this is 'bisection method' – Polymorphism Nov 08 '13 at 05:15

1 Answers1

0

This looks similar to Newton's method of calculating square root (derived from Newton-Raphson's method).

You can read more about this here.

It looks like:

  X(n+1) = (A/X(n) + X(n))/2
  It converges when X(n) = X(n+1) (that is in your case) or under some precision.

At each iteration, X(n) should get closer to the real root.

The purpose of ort is to hold X(n) and check for this convergence. When root converges, loop terminates. That is why ort is here.

You can read about Newton-Raphsone method (just google it) and you will be able to derive this equation.

doptimusprime
  • 9,115
  • 6
  • 52
  • 90