## File: Minimization-Examples.html

package info (click to toggle)
gsl-ref-html 2.3-1
• area: non-free
• in suites: bullseye, buster, sid
• size: 6,876 kB
• ctags: 4,574
• sloc: makefile: 35
 file content (167 lines) | stat: -rw-r--r-- 6,419 bytes parent folder | download
 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167  GNU Scientific Library – Reference Manual: Minimization Examples

35.8 Examples

The following program uses the Brent algorithm to find the minimum of the function f(x) = \cos(x) + 1, which occurs at x = \pi. The starting interval is (0,6), with an initial guess for the minimum of 2.

#include <stdio.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_math.h> #include <gsl/gsl_min.h>  double fn1 (double x, void * params) {   (void)(params); /* avoid unused parameter warning */   return cos(x) + 1.0; }  int main (void) {   int status;   int iter = 0, max_iter = 100;   const gsl_min_fminimizer_type *T;   gsl_min_fminimizer *s;   double m = 2.0, m_expected = M_PI;   double a = 0.0, b = 6.0;   gsl_function F;    F.function = &fn1;   F.params = 0;    T = gsl_min_fminimizer_brent;   s = gsl_min_fminimizer_alloc (T);   gsl_min_fminimizer_set (s, &F, m, a, b);    printf ("using %s method\n",           gsl_min_fminimizer_name (s));    printf ("%5s [%9s, %9s] %9s %10s %9s\n",           "iter", "lower", "upper", "min",           "err", "err(est)");    printf ("%5d [%.7f, %.7f] %.7f %+.7f %.7f\n",           iter, a, b,           m, m - m_expected, b - a);    do     {       iter++;       status = gsl_min_fminimizer_iterate (s);        m = gsl_min_fminimizer_x_minimum (s);       a = gsl_min_fminimizer_x_lower (s);       b = gsl_min_fminimizer_x_upper (s);        status          = gsl_min_test_interval (a, b, 0.001, 0.0);        if (status == GSL_SUCCESS)         printf ("Converged:\n");        printf ("%5d [%.7f, %.7f] "               "%.7f %+.7f %.7f\n",               iter, a, b,               m, m - m_expected, b - a);     }   while (status == GSL_CONTINUE && iter < max_iter);    gsl_min_fminimizer_free (s);    return status; }

Here are the results of the minimization procedure.

\$ ./a.out
using brent method  iter [    lower,     upper]       min        err  err(est)     0 [0.0000000, 6.0000000] 2.0000000 -1.1415927 6.0000000     1 [2.0000000, 6.0000000] 3.5278640 +0.3862713 4.0000000     2 [2.0000000, 3.5278640] 3.1748217 +0.0332290 1.5278640     3 [2.0000000, 3.1748217] 3.1264576 -0.0151351 1.1748217     4 [3.1264576, 3.1748217] 3.1414743 -0.0001183 0.0483641     5 [3.1414743, 3.1748217] 3.1415930 +0.0000004 0.0333474 Converged:     6 [3.1414743, 3.1415930] 3.1415927 +0.0000000 0.0001187