1 // Copyright 2015, Tobias Hermann and the FunctionalPlus contributors.
2 // https://github.com/Dobiasd/FunctionalPlus
3 // Distributed under the Boost Software License, Version 1.0.
4 // (See accompanying file LICENSE_1_0.txt or copy at
5 //  http://www.boost.org/LICENSE_1_0.txt)
6 
7 #include <doctest/doctest.h>
8 #include <fplus/fplus.hpp>
9 #include <array>
10 
11 TEST_CASE("optimize_test - minimize_downhill")
12 {
13     using namespace fplus;
14     const auto objective = [](const std::array<double, 1>& x)
__anon0692ca660102(const std::array<double, 1>& x) 15     {
16         return square(x[0] + 2) + 3;
17     };
18     {
19         const auto result = minimize_downhill<1>(
20             objective, 0.0001, {{123}});
21         REQUIRE(is_in_closed_interval_around(0.0001, -2.0, result[0]));
22     }
23     {
24         const auto result = minimize_downhill<1>(
25             objective, 0.0001, {{-42}}, maybe<double>(0.01));
26         REQUIRE(is_in_closed_interval_around(0.0001, -2.0, result[0]));
27     }
28     {
29         const auto result = minimize_downhill<1>(
30             objective, 0.0001, {{-2.000001}});
31         REQUIRE(is_in_closed_interval_around(0.0001, -2.0, result[0]));
32     }
33 
34     const auto objective_2d = [](const std::array<double, 2>& p)
__anon0692ca660202(const std::array<double, 2>& p) 35     {
36         const auto x = p[0];
37         const auto y = p[1];
38         return
39             abs(2*cube(x-3)) + 4*square(x+1) + 2*x +
40             abs(1*cube(y-7)) + 7*square(y-4) + 6*y;
41     };
42     {
43         const auto result1 = minimize_downhill<2>(
44             objective_2d, 0.0001, {{0,0}});
45         REQUIRE(is_in_closed_interval_around(0.001, 1.1946, result1[0]));
46         REQUIRE(is_in_closed_interval_around(0.001, 4.7025, result1[1]));
47 
48         const auto result2 = minimize_downhill<2>(
49             objective_2d, 0.0001, {{0,0}}, 0.123, 0.234);
50         REQUIRE(is_in_closed_interval_around(0.001, 1.1946, result2[0]));
51         REQUIRE(is_in_closed_interval_around(0.001, 4.7025, result2[1]));
52     }
53 }
54