File: bisection_method.cc

package info (click to toggle)
sopt 4.2.0%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,632 kB
  • sloc: cpp: 13,011; xml: 182; makefile: 6
file content (37 lines) | stat: -rw-r--r-- 1,242 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <catch2/catch_all.hpp>
#include <random>

#include <Eigen/Dense>

#include "sopt/bisection_method.h"
#include "sopt/types.h"

using Scalar = sopt::t_real;
using t_Vector = sopt::Vector<Scalar>;
using t_Matrix = sopt::Matrix<Scalar>;

constexpr Scalar a = -0.5;
constexpr Scalar b = 1.;
constexpr Scalar tol = 1e-4;
TEST_CASE("Bisection x^3") {
  using namespace sopt;
  sopt::logging::set_level("debug");
  std::function<Scalar(Scalar)> const func = [](const Scalar &x) -> Scalar { return x * x * x; };
  constexpr Scalar x0 = 0;
  const Scalar x0_est = bisection_method(func(x0), func, a, b, tol);
  CHECK(std::abs(x0_est - x0) <= tol);
}
TEST_CASE("Bisection f(x) = x") {
  using namespace sopt;
  std::function<Scalar(Scalar)> const func = [](const Scalar &x) -> Scalar { return x; };
  constexpr Scalar x0 = 0.23235104239409;
  const Scalar x0_est = bisection_method(func(x0), func, a, b, tol);
  CHECK(std::abs(x0_est - x0) <= tol);
}
TEST_CASE("Bisection exp()") {
  using namespace sopt;
  std::function<Scalar(Scalar)> const func = [](const Scalar &x) -> Scalar { return std::exp(-x); };
  constexpr Scalar x0 = 1;
  const Scalar x0_est = bisection_method(func(x0), func, a, b, tol);
  CHECK(std::abs(x0_est - x0) <= tol);
}