I am trying to make a function sqrt()
; the function I got is very slow. How can I make it faster?
#include <stdio.h>
#include <math.h>
double root(double x);
int main(){
printf("%f",root(3));
printf("\n%f",sqrt(3));
return 0;
}
double root(double x){
long double a[9];
long double b[9]={1.0,0.1,0.01,0.001,0.0001,0.00001,0.000001};
int i=0;
for(i=0;i<9;i++){
a[i]=0.0;
}
i=-1;
while(a[i]*a[i]!=x){
if(i==8)
i=-1;
i++;
a[i]+=b[i];
if(a[6]*a[6]>x)
return a[6];
else if(a[5]*a[5]==x)
return a[5];
else if(a[4]*a[4]==x)
return a[4];
}
return a[i];
}
I made this function on the basis that if you multiply all the numbers, you will be able to find the square root.
Summary of the original method
The method consists of carrying several counters in parallel in
a
. The countera[0]
advances from 1 to 1, while ita[1]
advances from 0.1 to 0.1, and so on.In each iteration, each counter is advanced and then it checks if the counter
a[4]
aa[6]
already has the desired root, returning it.In total, to calculate the root of 3, more than 1.7 million iterations were made.
New method
I collect the essence of the method: I will start by adding 1 to the tentative root until its square exceeds the received parameter. I will deduct 1 and then I will repeat the operation advancing from 0.1 to 0.1 until the square exceeds the parameter. I will subtract 0.1 and then continue with 0.01 and so on.
The calculation stops when exactly the root is found or until the factor to add is too small, and therefore does not produce a change in the root:
show
produces:
Improved version
The previous version only works for square roots of values over 1. This second version accepts any positive value.
The improvement is in the calculation of the starting root. The idea is to try with values 1, 10, 100, 1000, etc. until finding a value that exceeds the parameter. Then we successively divide by 10 until we find a value that is less than the parameter.
The resulting value is the starting tentative root.
Also simplify the detection of underflow , when the sum of the factor no longer contributes to the calculation of the root. In such a case, it returns directly to the caller.
produces: