/**************************************************** * Program to demonstrate Newton's method subroutine * * ------------------------------------------------- * * Reference: BASIC Scientific Subroutines, Vol. II * * By F.R. Ruckdeschel, BYTE/McGRAWW-HILL, 1981 [1]. * * * * C++ version by J-P Moreau, Paris. * * (www.jpmoreau.fr) * * ------------------------------------------------- * * SAMPLE RUN: * * * * (Example: find a real root of (x+1)^5) * * * * Input the initial guess: * * * * X0 = 0 * * * * Convergence factor: 1e-6 * * * * Maximum number of iterations: 30 * * * * * * The calculated zero is X = -0.998729 * * * * The associated Y value is Y = 0.000000 * * * * The number of steps was: 30 * * * ****************************************************/ #include #include double e,x0,yy; int m,n; /************************************************** Function subroutine */ double Y(double x, double *y1) { //derivative *y1 = 5+20*x+30*x*x+20*x*x*x+5*x*x*x*x; return (1+5*x+10*x*x+10*x*x*x+5*x*x*x*x+x*x*x*x*x); } /**************************************************/ /********************************************** * Newton's method subroutine * * ------------------------------------------- * * This routine calculates the zeroes of a * * function Y(x) by Newton's method. * * The routine requires an initial guess, x0, * * and a convergence factor, e. Also required * * is alimit on the number of iterations, m. * **********************************************/ void Newton() { double y1; n=0; // Get y and y1 e100: yy=Y(x0,&y1); // Update estimate x0=x0-(yy/y1); n++; if (n>=m) return; if (fabs(yy/y1)>e) goto e100; } void main() { printf("\n Input the initial guess:\n\n"); printf(" X0 = "); scanf("%lf",&x0); printf("\n Convergence factor: "); scanf("%lf",&e); printf("\n Maximum number of iterations: "); scanf("%d",&m); Newton(); // Call Newton routine printf("\n\n The calculated zero is X = %f\n\n",x0); printf(" The associated Y value is Y = %f\n\n",yy); printf(" The number of steps was: %d\n\n",n); } // End of file Newton.cpp