//#define XERR
#include "globals.ih"


// linear interpolation: for a -> f(a) = p, b -> f(b) = q
//                       compute f(x), where a <= x <= b as
//                       p + (q - p) / b - a) * (x - a)
//                    =  p + (q - p) * (x - a) / b - a)

// static
double Globals::findAge(DoubleVect const &cumProb, double prob)
{
    auto begin = cumProb.begin();
    auto last = upper_bound(begin, cumProb.end(), prob);

    auto first = lower_bound(begin, last, *(last - 1));

    return (first - begin) +
            (                           // interpolate 'prob' in the range of
                (last - first) *        // categories containing 'prob'
                    (prob - *first) /
                    ((last == cumProb.end() ? 1.0 : *last)  - *first)
            );
}
