#define eps 1e-9
double mySqrt(double a)
{
assert(a>=0);
double low=0,up=a;
double mid;
while (abs(up-low) >eps)
{
mid=(low+up)/2;
if (mid*mid>a)
{up=mid;
}
if (mid*mid<a)
{low=mid;
}
}
return mid;
}
double sqrtByNewton(double a)
{
double result=a;
while(abs(result*result-a)>eps)
{
result=(result+a/result)/2;
}
return result;
}//0x5f375a86
double newSqrt(double a)
{
double result=0x5f375a86;
while(abs(result*result-a)>eps)
{
result=(result+a/result)/2;
}
return result;
}//0x5f375a86
int main()
{
double a=65555.45;
clock_t start,end;
start=clock();
cout<<"sqrt: "<<sqrt(a)<<"__";
end=clock();cout<<"total time is:"<< (double)(end - start)<<endl;
start=clock();
cout<<"mySqrt: "<<mySqrt(a)<<"__";
end=clock();cout<<"total time is:"<<(double)(end - start)<<endl;
start=clock();
cout<<"sqrtByNewton:"<<sqrtByNewton(a)<<"__";
end=clock();cout<<"total time is:"<<(double)(end - start)<<endl;
start=clock();
cout<<"newSqrt: "<<newSqrt(a)<<"__";
end=clock();cout<<"total time is:"<<(double)(end - start)<<endl;
system("pause");
return 0;
double mySqrt(double a)
{
assert(a>=0);
double low=0,up=a;
double mid;
while (abs(up-low) >eps)
{
mid=(low+up)/2;
if (mid*mid>a)
{up=mid;
}
if (mid*mid<a)
{low=mid;
}
}
return mid;
}
double sqrtByNewton(double a)
{
double result=a;
while(abs(result*result-a)>eps)
{
result=(result+a/result)/2;
}
return result;
}//0x5f375a86
double newSqrt(double a)
{
double result=0x5f375a86;
while(abs(result*result-a)>eps)
{
result=(result+a/result)/2;
}
return result;
}//0x5f375a86
int main()
{
double a=65555.45;
clock_t start,end;
start=clock();
cout<<"sqrt: "<<sqrt(a)<<"__";
end=clock();cout<<"total time is:"<< (double)(end - start)<<endl;
start=clock();
cout<<"mySqrt: "<<mySqrt(a)<<"__";
end=clock();cout<<"total time is:"<<(double)(end - start)<<endl;
start=clock();
cout<<"sqrtByNewton:"<<sqrtByNewton(a)<<"__";
end=clock();cout<<"total time is:"<<(double)(end - start)<<endl;
start=clock();
cout<<"newSqrt: "<<newSqrt(a)<<"__";
end=clock();cout<<"total time is:"<<(double)(end - start)<<endl;
system("pause");
return 0;
}
2分法,牛顿迭代法,以及优化初值的改良牛顿迭代法
668

被折叠的 条评论
为什么被折叠?



