CosmoBolognaLib
Free Software C++/Python libraries for cosmological calculations
minimisation_gsl.cpp

This example shows how to minimize a function using the GSL libraries

// ============================================================================
// Example code: how to minimise a function using wrappers to the GSL libraries
// ============================================================================
#include "Func.h"
int main () {
try {
// define the (lambda) function to minimise
auto chi2 = [] (const double xx)
{
const double mean = 0.;
const double sigma = 1.;
return pow(xx-mean, 2)/(sigma*sigma);
};
// run the 1D minimisation GSL wrapper
const double starting_point = 99.;
const double min = -100.;
const double max = 100.;
const double res = cbl::wrapper::gsl::GSL_minimize_1D(chi2, starting_point, min, max);
std::cout << "result of the minimisation: " << res << std::endl;
// define a 2D (lambda) function to minimise
auto chi2_2 = [] (std::vector<double> &xx)
{
const double mean1 = 0.;
const double sigma1 = 1.;
const double mean2 = 1.;
const double sigma2 = 1.;
return pow(xx[0]-mean1, 2)/(sigma1*sigma1)+pow(xx[1]-mean2, 2)/(sigma2*sigma2);
};
// run the nD minimisation GSL wrapper
std::vector<double> starting_points = {5, 5};
std::vector<std::vector<double>> point_limits = {{-10, 10}, {-10, 10}};
const int maxiter = 10000;
std::vector<double> result = cbl::wrapper::gsl::GSL_minimize_nD(chi2_2, starting_points, point_limits, maxiter);
cbl::Print(result);
}
catch(cbl::glob::Exception &exc) { std::cerr << exc.what() << std::endl; exit(1); }
return 0;
}
Useful generic functions.
int main()
main function to create the logo of the CosmoBolognaLib
Definition: Logo.cpp:41
The class Exception.
Definition: Exception.h:111
const char * what() const noexcept override
the error description
Definition: Exception.h:203
double GSL_minimize_1D(FunctionDoubleDouble func, const double start, double min=par::defaultDouble, double max=-par::defaultDouble, const int max_iter=1000, const bool verbose=false)
minimize the provided function using GSL procedure
Definition: GSLwrapper.cpp:658
std::vector< double > GSL_minimize_nD(FunctionDoubleVector func, const std::vector< double > start, const std::vector< std::vector< double >> ranges, const unsigned int max_iter=1000, const double tol=1.e-6, const double epsilon=0.1)
minimize the provided function using GSL procedure
Definition: GSLwrapper.cpp:497
void Print(const T value, const int prec, const int ww, const std::string header="", const std::string end="\n", const bool use_coutCBL=true, std::ostream &stream=std::cout, const std::string colour=cbl::par::col_default)
function to print values with a proper homegenised format
Definition: Kernel.h:1142