// Arup Guha
// 1/25/2012
// Example of the Fixed Point Algorithm

#include <math.h>

double g(double x);
double getFixedPoint(double init, int maxiter);

int main() {
    printf("root is %lf\n", getFixedPoint(1,100));
    return 0;
}

// The specific function to test the algorithm.
double g(double x) {
    return sqrt(10-x*x*x)/2;
}

// Function that doesn't work.
double h(double x) {
    return x-x*x*x-4*x*x+10;
}

// Uses the initial guess init and runs the fixed point
// algorithm for a maximum of maxiter iterations.
double getFixedPoint(double init, int maxiter) {

    int i=1;

    // Limit the loop to maxiter iterations.
    while (i <= maxiter) {

        // Calculate the next value of p and print it.
        double p = g(init);
        printf("Iter %d: %.9lf\n", i, p);

        // See if this value is good enough.
        if (fabs(p - init) < 0.0000000001)
            return p;

        // Get ready for the next iteration.
        i++;
        init = p;
    }

    // Algorithm Failed.
    return -1;

}
