Question

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");
    }
}
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top