检查函数是否单调

Checking whether a function is monotonic or not

我有一个函数,我想检查它在特定域内是否是单调的。我可以替换域中的所有点并检查函数的单调性,但这是一种相当幼稚的方法。有没有其他方法可以检查函数在 C++ 中的域内是否是单调的?

这是由有限数量的点组成的域的特殊情况的示例实现(您无法使用 C++ 真正检查任意数学函数及其范围——memory/CPU 的能力不足以 store/check 不可数无限的范围):

std::function<double(double)> myFunction; //Set this to your function

std::vector<double> domain;  //Fill this in with your domain of interest

double previous_value = std::numeric_limits<double>::min();

auto first_non_mono_value = 
    std::find_if(domain.begin(), domain.end(),
        [&myFunction](double this_input)
        {
            double this_output = myFunction(this_input);
            if(previous_value > this_output)
                return true; //Violation of monotonic assumption

            previous_value = this_output;
            return false;  //Still may be monitonic (need to check next point)
        });

if(first_non_mono_value == domain.end())
{
    cout << "MONOTONIC" << endl;
}
else
{
    cout << "Not monotonic" << endl;
}

警告:我没有编译这个——所以它可能有错误,但你明白了大致的想法。

简单地说,你可以做类似的事情

enum monotonic_e {
    MONOTONIC_INCREASE, /* function is monotonically increasing */
    MONOTONIC_DECREASE, /* function is monotonically decreasing */
    MONOTONIC_CONSTANS, /* function is constant */
    MONOTONIC_NOT       /* function is not monotonic */   
};
double sign(double x) {
    return x < 0 ? -1. : (x > 0 ? 1. : 0.);
}
monotonic_e monotonic(const function< double(double) >& f,
                      double a, double b, double eps) {
    double x = a, y1 = f(x), y2 = f(x + eps);
    double d = y2 - y1;
    double s = sign(d);
    while( x < b ) {
        x += eps;
        y1 = y2;
        y2 = f(x + eps);
        d = y2 - y1;
        if( s == 0. ) {
            s = sign(d);
        }
        if( s * d < 0 ) {
            return MONOTONIC_NOT;
        }
    }
    return s > 0 ? MONOTONIC_INCREASE :
          (s < 0 ? MONOTONIC_DECREASE :
                   MONOTONIC_CONSTANS);
}

如果您必须检查很大范围的值,您可以通过将整个范围划分为较小的范围来并行化。