二分法和牛顿法求平方根

来源:互联网 发布:全景看房软件 编辑:程序博客网 时间:2024/05/16 18:12

二分法和牛顿法求平方根

C++代码

#include <iostream>#include <cmath>#include <iomanip>using namespace std;const double d = 0.000000001;double IsSquare(double x,double mid){    long a = round(mid);    if(a*a==x)    {        return a;    }    else{        return mid;    }}double SqrtBinary(double x) {        if (x == 0 || x == 1) {            return x;        } else {            double start = 0;            double end = x;            double mid;            while (true) {                mid = (start + end) / 2;                if (mid == x / mid || abs(mid - x / mid) <= d) {                    return IsSquare(x, mid);                } else if (mid < x / mid) {                    start = mid;                } else {                    end = mid;                }            }        }    }double SqrtNewton(double y0) {        if (y0 == 0 || y0 == 1) {            return y0;        } else {            double x = y0;            double nextX;            while (true) {                //牛顿迭代法                //y - f(x0)=f'(x0)(x-x0)                //x1 = x0 - f(x0)/f'(x0)                nextX = x - (x * x - y0) / (2 * x);                //nextX = (x * x + y0) / (2 * x); //这是我自己写的式子。通分就可以了                 if (abs(nextX - y0 / nextX) <= d) {                    return IsSquare(y0, nextX);                }                x = nextX;            }        }    }int main(){    double a = SqrtNewton(3);    cout<<setiosflags(ios::fixed)<<setprecision(20)<<a<<endl;    //1.73205081001472760427    //1.73205081001472738222    double b = SqrtBinary(3);    cout<<setiosflags(ios::fixed)<<setprecision(20)<<b<<endl;    return 0;}

问题与建议

  • 微博:@妥妥
  • 邮箱:iyatuo@gmail.com
0 0