// Root calculation (Newton + Secant method) #include #include using namespace std; double f(double x) { return (x-1.)*(x-2.)*(x-3.)*(x-4.)*(x-5.); } double fp(double x) { double h = 1E-5; return (f(x+h/2.)-f(x-h/2.))/h; } int main() { double a = 2.4, fa = f(a); double b = 2.5, fb = f(b); double c = 3.4, fc = f(c); if (fa*fc>0. && (a-b)*(c-b)<0.) { cout << "Bad initial boundary.\n"; return 0; } for(int step = 0; step<50; step++) { double delta = -fb/fp(b); double d = b + delta; double fd = f(d); if ((d-a)*(d-c)>0. || fabs(fd)>fabs(fb)) { if (fa*fb>0.) d = (b+c)*0.5; else d = (a+b)*0.5; fd = f(d); } cout << "Step: " << step <<", root = " << d << ", diff = " << fabs(d-3.) << endl; if (fabs(b-d)<1E-14) break; b = d; fb = fd; } }