// ---------------------------- // nzefplay.cpp // ---------------------------- #include "w.h" double g(double x) { return (cos(x) - x); } // test fun // Newton-Raphson with a step counter double nzef(fptype1 f, double x, int &count, double h = 0.01, double ytol = 1e-6) { double y = f(x), x1(1); count = 0; do { x1 = x - y*h/(f(x+h) - y); x = x1; y = f(x); count++; } while (fabs(y) > ytol); return x; } // -------------------------------------------------- void main() { nl(0); banner("nzefplay.cpp"); pl("g(x) = cos(x) - x"); nl(); precision(14); int count; double z = nzef(g, 0.5,count,0.001,1e-10); pl("The zero of g is z = ",z); pl("Check: g(z) = ",g(z)); pl("Number of steps = ",count); } /* output --------- Zefplay --------- f(x) = cos(x) - x The zero of g is z = 0.73908513321823 Check: g(z) = -5.1350483652561e-12 Number of steps = 4 */