/*================================================================== Written by: Roberto Mojica Last revision: 10 February 2007 -------------------------------------------------------------------- Programs that implement the Newton's method to find a root of a single variable function f(x) around some value of x. ==================================================================*/ #include #include #include using namespace std; //configuration #define PI 3.1415926535897932385 #define MAX_NUM_OF_ITERATIONS 10000 #define STARTING_POINT 1 #define EPS 1.0e-6 #define _Fx(X) exp(X)*log(X)-cos(X*X) #define _Fpx(X) exp(X)/X +exp(X)*log(X)+2*X*sin(X*X) //#define _Fx(X) log(X*X+2)*cos(X)+sin(X) //#define _Fpx(X) -log(X*X+2)*sin(X)+(2*X)/(X*X+2)+cos(X) //#define _Fx(X) exp(X)-sin(PI*X/3) //#define _Fpx(X) exp(X)-PI*cos(PI*X/3)/3 //#define _Fx(X) X*X-6*X+9 //#define _Fpx(X) 2*X-6 #define COL_WIDTH 20 void f(double x,double &fx,double &fpx) {fx=(_Fx(x)); fpx=(_Fpx(x)); return;} int main() { cout.setf(ios::fixed | ios::showpoint | ios::right); cout.precision(10); cout << ::setw(COL_WIDTH) << "x" << std::setw(COL_WIDTH) << "fx" << ::setw(COL_WIDTH) << "fpx" << endl; double x=STARTING_POINT,xc,fx,fpx; int iterations=0; do { f(x,fx,fpx); x=xc=x-fx/fpx; cout << ::setw(COL_WIDTH) << x << ::setw(COL_WIDTH) << fx << ::setw(COL_WIDTH) << fpx << ::setw(6) << iterations << endl; } while(fabs(fx) >= EPS && (iterations++) <= MAX_NUM_OF_ITERATIONS); cout << endl << xc << endl; system("pause"); return iterations; }