/*================================================================== Written by: Roberto Mojica Last revision: 10 February 2007 -------------------------------------------------------------------- Programs that finds a single root of a function f(x) on an interval [a,b] using the bisectional method or the false position method. ==================================================================*/ #include #include #include using namespace std; //configuration #define PI 3.1415926535897932385 #define MAX_NUM_OF_ITERATIONS 10000 #define LEFT_END_POINT 1 #define RIGHT_END_POINT 4 #define EPS 1.0e-6 #define _Fx(X) exp(X)*log(X)-cos(X*X) //#define _Fx(X) log((X*X)+2)*cos(X)+sin(X) //#define _Fx(X) exp(X)-sin((PI*X)/3) //#define _Fx(X) X*X-6*X+9 double f(double x) {return (_Fx(x));} int main() { cout.setf(ios::fixed | ios::showpoint); cout.precision(10); double xO,xL=LEFT_END_POINT,xR=RIGHT_END_POINT; int iterations=0; if(f(xL)*f(xR) <= 0) { while (fabs(xR-xL) >= EPS && (iterations++) <= MAX_NUM_OF_ITERATIONS) { xO=(xL+xR)/2.0; //bisectional //xO=xR-f(xR)*(xR-xL)/(f(xR)-f(xL)); //false position if((f(xL)*f(xO)) <= 0) xR=xO; else xL=xO; } cout << "xO = " << xO << endl; } cout << "iterations = " << iterations << endl; system("pause"); return iterations; }