// Arup Guha
// 1/27/2012
// Example of the Secant Algorithm finding a root for f(x) = -x^3 - cos(x)

#include <math.h>

double f(double x);
double fprime(double x);
double secantGetRoot(double p0, double p1, int maxiter);

int main() {

    printf("root is %lf\n", secantGetRoot(-1,-.5,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 secantGetRoot(double p0, double p1, int maxiter) {

    int i=1;

    while (i <= maxiter) {

        // Avoid divide by zero.
        if (fprime(p0) == 0)
            p0 += .01;

        double p2 = p1 - f(p1)*(p1-p0)/(f(p1)-f(p0));
        printf("Iter %d: %.9lf\n", i, p2);

        if (fabs(p1 - p0) < 0.000000001)
            return p1;

        i++;
        p0 = p1;
        p1 = p2;
    }

    // Algorithm Failed.
    return -1;

}
