gpt4 book ai didi

c++ - 检查函数是否单调

转载 作者:行者123 更新时间:2023-11-28 00:18:47 25 4
gpt4 key购买 nike

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

最佳答案

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

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);
}

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

关于c++ - 检查函数是否单调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28642656/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com