#include #include using namespace std; double f (double x) { return sin (x) * x * x + exp (-x); // return cos(x)*x*x+1/log(2.0+x*x); } double fp (double x) { return cos (x) * x * x + 2 * sin (x) * x - exp (-x); // return -sin(x)*x*x+2.0*cos(x)*x-2.0/pow(log(2.0+x*x),2.0)*x/(2.0+x*x); } double opt (double x1, double x2, double x3, double y1, double y2, double y3) { return (x3 * x3 * (y1 - y2) + x1 * x1 * (y2 - y3) + x2 * x2 * (y3 - y1)) / (2.0 * (x3 * (y1 - y2) + x1 * (y2 - y3) + x2 * (y3 - y1))); } main () { const double tol = pow (10.0, -6.0); double x = -1.5; double xold; double x1, x2, x3; double a1, a2, a3; cout << x << "\t" << f (x) << "\n"; while (1) { double ngrad = -fp (x); if (ngrad == 0.0) break; a1 = 1; while (f (x + a1 * ngrad) > f (x) and fabs (a1 * ngrad) > tol) { a1 /= 2.0; } x1 = x + a1 * ngrad; a2 = a1 / 2.0; x2 = x + a2 * ngrad; a3 = opt (0, a1, a2, f (x), f (x1), f (x2)); x3 = x + a3 * ngrad; xold = x; if (f (x3) < f (x1)) x = x3; else x = x1; // cout << x << "\t" << f(x) << "\n"; cout << x << "\t" << f (x) << "\t" << xold << "\t" << x1 << "\t" << x2 << "\t" << x3 << "\n"; if (fabs (xold - x) < tol) break; } }