C/C++:二分法查找近似根

来源:互联网 发布:淘宝发展史宣传片 编辑:程序博客网 时间:2024/05/17 04:55

问题

求出y=2*x^3-4*x^2+3*x-6在[-10,10]上的根


#include <iostream>#include <stdlib.h>#include <math.h>using namespace std;double Function(double x){    return 2.0*pow(x, 3) - 4.0*pow(x, 2) + 3.0*x - 6.0;}int main(void){    double fEps,fAccuracy,fLeftEndPoint,fRightEndPoint,fMiddlePoint, fLeftEndPointFunction, fRightEndPointFunction,fMiddlePointFunction;    cout << "请输入你想要的精度" << endl;    cin >> fEps;    fLeftEndPoint = -10.0; fRightEndPoint = 10.0;    fAccuracy = fRightEndPoint - fLeftEndPoint;    fMiddlePoint = (fRightEndPoint + fLeftEndPoint) / 2.0;    if (abs(fEps) > fAccuracy) cout << "您想找的近似根为" << fMiddlePoint << endl;    while (abs(fEps)<fAccuracy)    {        fLeftEndPointFunction = Function(fLeftEndPoint);        if (fLeftEndPointFunction==0)        {            cout << "这是个精确根" << fLeftEndPoint << endl; break;        }        fRightEndPointFunction = Function(fRightEndPoint);        if (fRightEndPointFunction==0)        {            cout << "这是个精确根" << fRightEndPoint << endl; break;        }        fMiddlePointFunction = Function(fMiddlePoint);        if (fLeftEndPointFunction*fMiddlePointFunction<0)        {            fRightEndPoint = fMiddlePoint;            fAccuracy = fRightEndPoint - fLeftEndPoint;            fMiddlePoint = (fRightEndPoint + fLeftEndPoint) / 2.0;            if (abs(fEps) > fAccuracy)            {                cout << "您想找的近似根为" << fMiddlePoint << endl;                break;            }        }        if (fRightEndPointFunction*fMiddlePointFunction<0)        {            fLeftEndPoint = fMiddlePoint;            fAccuracy = fRightEndPoint - fLeftEndPoint;            fMiddlePoint = (fRightEndPoint + fLeftEndPoint) / 2.0;            if (abs(fEps) > fAccuracy)            {                cout << "您想找的近似根为" << fMiddlePoint << endl;                break;            }        }    }    system("pause");    return 0;}

注意:使用二分法求方程根需要 左侧的函数表达式在该区间上是单调的

0 0
原创粉丝点击