欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

sqrt的实现-牛顿迭代法和二分法对比

程序员文章站 2022-06-03 12:22:04
...

1. 二分法实现sqrt()

#include<iostream>
#include<cmath>
using namespace std;
#define eps 1e-2 

float sqrt(float n)
{
    if(n < 0) return 0;
    float mid,last;
    float low,up;
    low = 0,up = n;
    mid=(low + up)/2;
    do{
        if(mid*mid >n)  
            up = mid;
        else    
            low = mid;
        last = mid;
        mid = (up + low)/2;
    }while(abs(mid-last)>eps);
    return mid;
}

int main(){
    cout<<"sqrt(65535) is "<<sqrt(65535)<<endl;
    return 0;
} 

2. 牛顿迭代法实现sqrt()

#include<iostream>
#include<cmath>
using namespace std;
#define eps 1e-2 

float sqrt(float x)
{
    float val = x;//最终
    float last;//保存上一个计算的值
    do
    {
        last = val;
        val =(val + x/val) / 2;
    }while(abs(val-last) > eps);
    return val;
}

int main(){
    cout<<"sqrt(65535) is "<<sqrt(65535)<<endl;
    return 0;
} 

参考链接:

http://blog.csdn.net/qq_26499321/article/details/73724763