From 393a2cbeaa1b65ba4d076d18d1ac015a41f707e6 Mon Sep 17 00:00:00 2001 From: KRM7 <70973547+KRM7@users.noreply.github.com> Date: Tue, 15 Aug 2023 18:46:41 +0200 Subject: [PATCH] Create 10_fp_context.cpp --- examples/10_fp_context.cpp | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 examples/10_fp_context.cpp diff --git a/examples/10_fp_context.cpp b/examples/10_fp_context.cpp new file mode 100644 index 00000000..69a0bfdf --- /dev/null +++ b/examples/10_fp_context.cpp @@ -0,0 +1,37 @@ +/* Example showing how to change the tolerances used for floating-point comparisons in the GA. */ + +#include "gapp.hpp" // include everything +#include +#include + +using namespace gapp; + +class SinX : public FitnessFunction +{ + FitnessVector invoke(const Chromosome& x) const override { return { std::sin(x[0]) }; } +}; + +int main() +{ + std::cout << "The default absolute tolerance used is " << math::Tolerances::abs() << "\n"; + std::cout << "The default relative tolerance around 1.0 is " << math::Tolerances::rel(1.0) << "\n"; + + { + auto solutions = RCGA{}.solve(SinX{}, Bounds{ 0.0, 3.14 }); + std::cout << "The maximum of sin(x) in [0.0, 3.14] is at x = " << solutions[0].chromosome[0] << "\n"; + } + + { + math::ScopedTolerances _(/* abs = */ 0.1, /* rel = */ 0.1); + + auto solutions = RCGA{}.solve(SinX{}, Bounds{ 0.0, 3.14 }); + std::cout << "The maximum of sin(x) in [0.0, 3.14] is at x = " << solutions[0].chromosome[0] << "\n"; + } + + { + math::ScopedTolerances _(/* abs = */ 0.0, /* rel = */ 0.0); + + auto solutions = RCGA{}.solve(SinX{}, Bounds{ 0.0, 3.14 }); + std::cout << "The maximum of sin(x) in [0.0, 3.14] is at x = " << solutions[0].chromosome[0] << "\n"; + } +}