#include "regula_falsi.h"

double regula_falsi(func_ptr f, double s, double t, double e,
        unsigned int *steps, unsigned int m) {
    int side = 0;
    double r, fr, fs = f(s), ft = f(t);

    for( ; *steps < m; (*steps)++ ) {
        r = (fs * t - ft * s) / (fs - ft);

        if( fabs(t - s) < e * fabs(t + s) ) {
            (*steps)++;
            break;
        }

        fr = f(r);

        if( fr * ft > 0 ) {
            t = r;
            ft = fr;

            if( side == -1 )
                fs /= 2;

            side = -1;
        } else if (fs * fr > 0) {
            s = r;
            fs = fr;

            if( side == 1 )
                ft /= 2;

            side = 1;
        } else {
            (*steps)++;
            break;
        }
    }

    return r;
}

