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.