Calculating the square root without library methods

How can I calculate the square root without using sqrt(n) and n^0.5?

Author: pavel, 2016-09-15

3 answers

The question actually has many solutions.

The most banal method is the half - division method.

double l = 0;
double r = 1e100; //большое число
double m;
while (r - l > 1e-8){ //точность
    m = l + (r - l)/2;
    if (m*m > n) l = m;
            else r = m; 
}
//ответ в l

There are more original ways, for example, simulating a calculation in a column (here is example, I will not give the code )

The method is more for C, but I think it can be used in Java. Explanation

float Q_rsqrt( float number )
{
    long i;
    float x2, y;
    const float threehalfs = 1.5F;

    x2 = number * 0.5F;
    y  = number;
    i  = * ( long * ) &y;                       
    i  = 0x5f3759df - ( i >> 1 );                
    y  = * ( float * ) &i;
    y  = y * ( threehalfs - ( x2 * y * y ) );   // 1 итерация
//  y  = y * ( threehalfs - ( x2 * y * y ) );   // 2 итерация, можно удалить
    return 1/y;
}

You can use the logarithms

return Math.exp( Math.log(n) / 2);

You can use numerical methods, such as the method Newton

double x = 1;
for (;;) {
   double nx = (x + n / x) / 2;
   if (abs (x - nx) < 1e-10)  break; //точность
   x = nx;
}

There are many other ways, it all depends on the specific requirements.

 13
Author: pavel, 2016-09-15 07:48:06

Write your own square root calculation function using Newton's (tangent) method using the formula

enter a description of the image here :

public static double sqrt(int number) {
    double t;     
    double squareRoot = number / 2;     
    do {
        t = squareRoot;
        squareRoot = (t + (number / t)) / 2;
    } while ((t - squareRoot) != 0);     
    return squareRoot;
}

Ideone

 5
Author: Denis, 2016-09-15 08:31:08

It all depends on the context of the task. The various methods have already been described. There is another option for the case if the range of input parameters is approximately known. You can just make a table with ready-made answers.

When we did a course on microchip technology for 8-bit systems, the simplest and fastest solution was a 256-cell ROM with the answers already sewn there. But the teacher did not agree with this approach. I offered to "count"it all the same.

 1
Author: newman, 2017-02-15 21:36:44