/* * Copyright Nick Thompson, 2024 * Use, modification and distribution are subject to the * Boost Software License, Version 1.0. (See accompanying file * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef TEST_FUNCTIONS_FOR_OPTIMIZATION_HPP #define TEST_FUNCTIONS_FOR_OPTIMIZATION_HPP #include #include #include /* simple n-d quadratic function */ template RealType quadratic(std::vector& x) { RealType res{ 0.0 }; for (auto& item : x) { res += item * item; } return res; } template RealType quadratic_high_cond_2D(std::vector& x) { return 1000 * x[0] * x[0] + x[1] * x[1]; } // Taken from: https://en.wikipedia.org/wiki/Test_functions_for_optimization template Real ackley(std::array const& v) { using boost::math::constants::e; using boost::math::constants::two_pi; using std::cos; using std::exp; using std::sqrt; Real x = v[0]; Real y = v[1]; Real arg1 = -sqrt((x * x + y * y) / 2) / 5; Real arg2 = cos(two_pi() * x) + cos(two_pi() * y); return -20 * exp(arg1) - exp(arg2 / 2) + 20 + e(); } template auto rosenbrock_saddle(std::array const& v) -> Real { Real x{ v[0] }; Real y{ v[1] }; return static_cast(100 * (x * x - y) * (x * x - y) + (1 - x) * (1 - x)); } template Real rastrigin(std::vector const& v) { using boost::math::constants::two_pi; using std::cos; auto A = static_cast(10); auto y = static_cast(10 * v.size()); for (auto x : v) { y += x * x - A * cos(two_pi() * x); } return y; } // Useful for testing return-type != scalar argument type, // and robustness to NaNs: double sphere(std::vector const& v) { double r = 0.0; for (auto x : v) { double x_ = static_cast(x); r += x_ * x_; } if (r >= 1) { return std::numeric_limits::quiet_NaN(); } return r; } template Real three_hump_camel(std::array const& v) { Real x = v[0]; Real y = v[1]; auto xsq = x * x; return 2 * xsq - (1 + Real(1) / Real(20)) * xsq * xsq + xsq * xsq * xsq / 6 + x * y + y * y; } // Minima occurs at (3, 1/2) with value 0: template Real beale(std::array const& v) { Real x = v[0]; Real y = v[1]; Real t1 = Real(3) / Real(2) - x + x * y; Real t2 = Real(9) / Real(4) - x + x * y * y; Real t3 = Real(21) / Real(8) - x + x * y * y * y; return t1 * t1 + t2 * t2 + t3 * t3; } #endif