// Arup Guha
// 1/27/2012
// Example of Newton's Algorithm

#include <math.h>

double f(double x);
double fprime(double x);
double getRoot(double init, int maxiter);

int main() {

    printf("root is %lf\n", getRoot(-1,100));
    return 0;
}

// The specific function to test the algorithm.
double f(double x) {
    return -x*x*x - cos(x);
}

double fprime(double x) {
    return -3*x*x + sin(x);
}

// Uses the initial guess init and runs the fixed point
// algorithm for a maximum of maxiter iterations.
double getRoot(double p0, int maxiter) {

    int i=1;

    while (i <= maxiter) {

        // Avoid divide by zero.
        if (fprime(p0) == 0)
            p0 += .01;

        double p1 = p0 - f(p0)/fprime(p0);
        printf("Iter %d: %.9lf\n", i, p1);

        if (fabs(p1 - p0) < 0.000000001)
            return p1;

        i++;
        p0 = p1;
    }

    // Algorithm Failed.
    return -1;

}
