Search code examples
calgorithmsquare-root

Algorithm to find the square root


Playing around with formulas in C, I realized that I found a formula for calculating the square root of a number. I would like to know if such an algorithm already exists, or if it is widely known to scholarly mathematicians. I'm sending the code so you guys take a look. I tested it in C++ Builder with TimeSpan and it is almost as fast as the language's standard sqrt function, which is written in assembly. If you can take a look and see if this is interesting I would appreciate it. It's for a school assignment.

Ps: for most numbers it gets the precision of the sqrt function to about 20 iterations.

#include <stdio.h>
#include <stdlib.h>

int findInitial(double number){

    int i,n,res;
    n = trunc(number);
    res = 0;
    i = 1;
    while (1){
        if ((i * i) >= n) {
           res = i - 1;
           break;
        }
        i++;
    }
    return res;
}

int main(int argc, char *argv[])
{
    int i = 0;
    double number = 23;
    int initial = findInitial(number);
    double f = number;
    double e;
    double temp = 1;
    
    printf("%.18f\n",sqrt(number));

    while ((temp < -0.000000000000000001) ^ (temp > 0.000000000000000001)){
        e = f - (f * f - number)/(f - initial);
        if (temp == ((f - e) * -1)) {
          break;
        }
        temp = f - e;
        f = e;
        i++;
        printf("%d - %.18f\n",i,f*-1);
    }

    system("pause");    
    return 0;
}

Ps2: I had to create a conditional because in the case of number 23, the variable temp oscillated from negative to positive and never reached the desired precision.


Solution

  • Aside from this not working for all legal inputs (so it's, strictly speaking, not a method for finding the square root of numbers in general, just for a few of the possible numbers), this is basically Newton's method for approximating the square root.

    Using Newton's method for this is like the standard example for a numerical math lecture, so Wikipedia has a concrete section on Newton's Method for finding Square Roots.

    Your method is not quite Newton's method, because the convergence of that works for all inputs, by the fortune of dividing by the derivative of the function you want to find a null of (which is f*f-number in your case).