0

I am trying to find the minimum of a function of mine using C++. However, upon attempting to run the code, I am returned the following error:

gsl: fsolver.c:117: ERROR: x_minimum must lie inside interval (lower < x < upper)

Despite knowing that my x_lo and x_hi values are definitely encapsulating the minimum, calculated in another bit of software.

I am curious as to what I am doing wrong - I made my function continuous, defined my range, and a relatively close first guess, and yet I am still plagued with this error. I am not very good with the GSL - in fact, I had never used it before.

Code for reference:

#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;
}
kalle
  • 425
  • 1
  • 6
  • 17
  • Why do you have a for loop in example function? The return exits on the first iteration. I'd try a simple function that returns a constant to verify that everything is configured correctly. – Wayne Tanner Feb 21 '16 at 22:07
  • Actually, example function is only being evaluated at X = 0.001 since you overwrite the parameter value in the loop initializer. – Wayne Tanner Feb 21 '16 at 22:17

0 Answers0