/******************************************************************** * Find a real root of a real function F(x) by the Zeroin method * * ----------------------------------------------------------------- * * SAMPLE RUN: * * (Example 1: Find a root of function 5x - exp(x) between 0 and 1) * * * * The output file tzeroin.lst contains: * * * * ----------------------------------------------------------------- * * Zeroin method for real valued, nonlinear functions * *------------------------------------------------------------------ * * Example n° 1 * * * * f = 5 * x - exp (x) * * Starting value x0 = 0.000000 * * Return code = 0 * * Root = 0.2591711018190740 * * Function value = 6.661338e-016 * * Function calls = 8 * * * * Absolute error = 0.000000 * * Relative error = 0.000000 * * * * ----------------------------------------------------------------- * * Ref.: "Numerical Algorithms with C By G. Engeln-Mueller and * * F. Uhlig, Springer-Verlag, 1996" [BIBLI 11]. * * * * C++ version by J-P Moreau, Paris. * * (www.jpmoreau.fr) * ********************************************************************/ #include "basis.h" // uses file fzeroin.cpp #include "tfunc1.h" // --------------------- int zeroin (REALFCT, REAL *, REAL *, int, char *, REAL, REAL *, REAL *, int * ); int main (void) { int i, rc, nmax, niter; REAL abserr=100*MACH_EPS,relerr=1000*MACH_EPS,x1,x2, f; REAL (*fct) (REAL); char *text; FILE *fp; fp=fopen("tzeroin.lst","w"); // output file WriteHead(fp," Zeroin method for real valued, nonlinear functions"); nmax = 100; for (i = 1; i <= 6; i++) { switch (i) { case 1: x1 = ZERO; x2 = ONE; fct = f1; text = "f = 5 * x - exp (x)"; break; case 2: x1 = 0.5; x2 = 1.5; fct = f2; text = "f = (((((x-6)*x+15)*x-20)*x+15)*x-6)*x+1"; break; case 3: x1 = 3.0; x2 = 3.5; fct = f3; text = "f = sin (x)"; break; case 4: x1 = -2.0; x2 = -1.5; fct = f4; text = "f = 1 + sin (x)"; break; case 5: x1 = TWO; x2 = 3.0; fct = f5; text = "f = exp(x) -(1.0 + x + x*x*0.5)"; break; case 6: x1 = TWO; x2 = 3.0; fct = f6; text = "f = (x-1.0)*(x-1.0)*( sin(PI*x) - " "log(fabs(2.0*x/(x+1.0)))"; break; default: return (1); } fprintf (fp," Example n° %d\n\n",i); fprintf (fp," %s\n", text); fprintf (fp," Starting value x0 = "); fprintf (fp,FORMAT_LF, x1); fprintf (fp,"\n"); rc = zeroin (fct, &abserr, &relerr, nmax, "tzeroin.log", x1, &x2, &f, &niter); fprintf (fp," Return code = % d\n", rc); fprintf (fp," Root = "); fprintf (fp,FORMAT_2016LF, x2); fprintf (fp,"\n Function value = "); fprintf (fp,FORMAT_LE, f); fprintf (fp,"\n Function calls = % d\n", niter); fprintf (fp,"\n Absolute error = %f",abserr); fprintf (fp,"\n Relative error = %f\n\n",relerr); WriteEnd(fp); } fclose(fp); printf("\nResults in tzeroin.lst.\n\n"); return (0); } //end of file tzeroin.cpp