/*************************************************** * Root of a non-linear Equation By Lagrange * * ------------------------------------------------ * * REF.: "Méthode de calcul numérique - Programmes * * en Basic By Claude Nowakowski, PS1 1981". * * * * ------------------------------------------------ * * SAMPLE RUN: * * * * Find a root of equation: X - E SIN X * * * * Input Starting, Ending X: 1 10 * * Input max. error: 1e-5 * * * * Root = 2.199123 * * Iterations: 7 * * Y = -5.409158e-007 * * * * * * C++ Version By J-P Moreau, Paris. * * (www.jpmoreau.fr) * ***************************************************/ #include #include // Labels: e100, e200 #define MAXITER 50 double E,XB,X1,X2,YB,Y1,Y2; int K; char rep[2]; // User-defined non-linear function double FUNC (double X) { return (X - 2.718281828 * sin(X)); } void main() { printf("\n Input Starting, Ending X: "); scanf("%lf %lf", &X1, &X2); printf(" Input max.error: "); scanf("%lf", &E); printf("\n"); Y1 = FUNC(X1); Y2 = FUNC(X2); if (Y1 * Y2 > 0) { printf(" Bad choice for X1, X2!\n"); goto e200; } if (fabs(Y1 * Y2) < 1e-10) { printf(" X1 or X2 is a root!\n"); goto e200; } // main iteration loop for (K=1; K<=MAXITER; K++) { XB = X2 - (X2 - X1) * Y2 / (Y2 - Y1); if (fabs(X1 - XB) < E) goto e100; // normal exit YB = FUNC(XB); if (Y1 * YB < 0) { X2 = XB; Y2 = YB; } else { X1 = XB; Y1 = YB; } } printf(" No root found!\n"); goto e200; e100: printf(" Root = %f\n", XB); printf(" Iterations: %d\n", K); printf(" Y = %e\n\n", FUNC(XB)); e200: scanf("%s", rep); } // End of file Lagrange1.cpp