// Programme to use Newton's method to find a zero of a function.
//
//  Function f(x) returns the value of the function whose zero is sought
//       deriv(x) returns the first derivative of the function
//
// Note that the starting guess for the zero must be close enough to the actual zero so the method doesn't jump to some other zero
// (if one exists).

#include <cmath>
#include <iostream>


using namespace std;

// Function whose zero is to be found.

double f(double x)
{
    return cos(2*x) + 1 - x;
}

// Derivative of the function

double deriv(double x)
{
    return -2*sin(2*x) - 1;
}

int main()
{
    long   nmax;
    double xn    = 0.0;
    double delta = 0.0;
    
	cout << "Enter maxmimum tries and initial guess" << endl;
    cin >> nmax >> xn;
    
    cout << "Using parameters: " << nmax << " " << xn << endl;
        
    for(long i=0; i< nmax; ++i)
    {
        delta = -f(xn)/deriv(xn);
                
        std::cout << i << " " << xn << " " << delta << " " << f(xn) << endl;
        
        xn += delta;
        
    }

	return 0;
}

