1

I pulled this code from http://blog.shay.co/newtons-method/:

//a - the number to square root
//times - the number of iterations
public double Sqrt(double a, int times)
{
    if (a < 0)
        throw new Exception("Can not sqrt a negative number");
    double x = 1;
    while (times-- > 0)
        x = x / 2 + a / (2 * x);
    return x;
}

What is a good rule of thumb for the number of iterations on a number, if one exists? (For example, "Use n/2 iterations".)

Evorlor
  • 7,263
  • 17
  • 70
  • 141

2 Answers2

5

What is a good rule of thumb for the number of iterations on a number, if one exists?

Newton's method has quadratic convergence, ie. at every step of the algorithm, the number of significant digits in the answer doubles. Thus the algorithm computes square roots upto D digits of precision in O(log D) time. Thus the number of iterations in your loop will depend upon the accuracy expected. So to have a fine grained control over the accuracy of the result, you can add a check in your code that returns the answer when the estimate is not outside the error bounds.

public double Sqrt(double a){
    if (a < 0)
        throw new Exception("Can not sqrt a negative number");
    double error = 0.00001;
    double x = 1;
    while (true){
        double val = x*x;
        if(abs(val-a) <= error)
             return x;
        x = x / 2 + a / (2 * x);
    }
}
Nikunj Banka
  • 11,117
  • 16
  • 74
  • 112
  • 1
    wow! that is so much better of an answer than i expected! thanks!!!! i have another question too if u dont mind...do u know if there will be a difference here for me using double vs float? – Evorlor Apr 26 '14 at 06:48
  • 1
    Double offers more digits of precision than a float. So for more accurate answers use a double data type. You can see this for more http://stackoverflow.com/questions/1074474/should-i-use-double-or-float . And the same question for C# http://stackoverflow.com/questions/417568/float-vs-double-performance – Nikunj Banka Apr 26 '14 at 06:51
0

If you want a guaranteed relative accuracy with a fixed number of iterations, then prepare the iteration by dividing a by 4 until the result is between 1/2 and 2. Or multiply if starting with a value smaller than 1. Remember the number of divisions, since

sqrt(a)=2^k*sqrt(4^(-k)*a)

requires to multiply the result with a like number of factors 2. Then the relative error for the square root of the reduced a will fall like

3*(1/6)^(2^m)

after m iterations, or faster, according to

(x[m]-sqrt(a))/(x[m]+sqrt(a)) = ( (1-sqrt(a))/(1+sqrt(a)) )^(2^m)

You can extract and manipulate the required powers of 4 and 2 fastest by using the access functions to the floating point exponent, frexp and ldexp in the C math library, similar methods in the Double class in Java.

Lutz Lehmann
  • 25,219
  • 2
  • 22
  • 51