GNU科学图书馆:尽管在范围内,但找不到最小值

时间:2016-02-21 18:51:08

标签: c++ gnu gsl minimization

我正在尝试使用C ++找到我的函数的最小值。但是,在尝试运行代码时,我返回以下错误:

gsl:fsolver.c:117:错误:x_minimum必须位于区间内(低于< x< upper)

尽管知道我的x_lo和x_hi值肯定是封装了最小值,在另一个软件中计算。

我很好奇我做错了什么 - 我使我的功能连续,定义了我的范围,并且相对接近的第一次猜测,但我仍然受到这个错误的困扰。我对GSL不是很了解 - 事实上,我之前从未使用它。

参考代码:

#include <iostream>
#include <gsl/gsl_roots.h>
#include <gsl/gsl_min.h>

struct Params {
    double ac, b1, c, d, f, g, mass;
};
double examplefunction(double x, void* param){
    Params* p = (Params*)param;
    for (x = 0.001; x < 0.45; x += 0.01) {
        return (p->ac*((p->b1/x)+((pow(p->d,2))/(p->f*(pow((x-p->d),2)))-exp((-p->c*((pow((x-p->b1),2))/(2*p->ac)))))))+(-p->mass*p->g*x);
    }
}

int main() {
    double x_lo = 0.3;
    double x_hi = 0.5;
    double m = -0.5;
    Params args = {1.0, 0.1, 100.0, 0.5, 2500.0, 9.8, 0.3};
    gsl_min_fminimizer* solver;
    gsl_function fwrapper;
    solver = gsl_min_fminimizer_alloc(gsl_min_fminimizer_brent);
    fwrapper.function = examplefunction;
    fwrapper.params = &args;
    gsl_min_fminimizer_set(solver, &fwrapper, m, x_lo, x_hi);
    std::cout << " iter [ lower, upper] root err\n";
    int status = 1;
    for (int iter=0; status and iter < 100; ++iter) {
        gsl_min_fminimizer_iterate(solver);
        double x_rt = gsl_min_fminimizer_x_minimum(solver);
        double x_lo = gsl_min_fminimizer_x_lower(solver);
        double x_hi = gsl_min_fminimizer_x_upper(solver);
        std::cout << iter <<" "<< x_lo <<" "<< x_hi
        <<" "<< x_rt <<" "<< x_hi - x_lo << "\n";
        status = gsl_min_test_interval(x_lo,x_hi,0,0.001);
    }
    gsl_min_fminimizer_free(solver);
    return status;
}

0 个答案:

没有答案