/* newton-raphson method for root finding. */ #include #include #include using std::endl; using std::cout; // define function: double func_y(double x){ return pow(x,3.0) + 1.0; } //define first derivative of function: double func_dydx(double s){ return 3.0*pow(s,2.0); } int main() { int N= 0; int N_limit = 1000; // max number of trys double s = -1.1; // initial guess for root double tol = 1.0e-5; // tolerance for finding zero while ((fabs(func_y(s)) >= tol) && (N < N_limit)){ s = s - func_y(s)/func_dydx(s); ++N; } if(N >= N_limit){ cout << "iteration limit exceeded" << endl; return 0; } if (N <= N_limit){ cout << "estimated root = " << s << " with " << N << " iterations." << endl; } return 0; }