17#ifndef __math_golden_section_search_h__
18#define __math_golden_section_search_h__
49 template <
class FunctionType,
typename ValueType>
51 const std::string& message,
53 ValueType init_estimate,
55 ValueType tolerance = 0.01) {
57 std::unique_ptr<ProgressBar> progress (message.size() ?
new ProgressBar (message) :
nullptr);
59 const ValueType g1 = 0.61803399, g2 = 1 - g1;
60 ValueType x0 = min_bound, x1, x2, x3 = max_bound;
62 if (
abs(max_bound - init_estimate) >
abs(init_estimate - min_bound)) {
64 x2 = init_estimate + g2 * (max_bound - init_estimate);
67 x1 = init_estimate - g2 * (init_estimate - min_bound);
70 ValueType f1 = function(x1);
71 ValueType f2 = function(x2);
73 while (tolerance * (
abs(x1) +
abs(x2)) <
abs(x3 - x0)) {
77 x2 = g1 * x1 + g2 * x3;
78 f1 = f2, f2 = function(x2);
82 x1 = g1 * x2 + g2 * x0;
83 f2 = f1, f1 = function(x1);
88 return f1 < f2 ? x1 : x2;
implements a progress meter to provide feedback to the user
ValueType golden_section_search(FunctionType &function, const std::string &message, ValueType min_bound, ValueType init_estimate, ValueType max_bound, ValueType tolerance=0.01)
Computes the minimum of a 1D function using a golden section search.
constexpr std::enable_if< std::is_arithmetic< X >::value &&std::is_unsigned< X >::value, X >::type abs(X x)