From d9f06efb57824cd7e0314cf001279b8c15985376 Mon Sep 17 00:00:00 2001 From: lisyarus Date: Sat, 24 Oct 2020 19:36:58 +0300 Subject: [PATCH] Add quadratic solver --- libs/geom/include/psemek/geom/math.hpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/libs/geom/include/psemek/geom/math.hpp b/libs/geom/include/psemek/geom/math.hpp index 65750306..8eea2b31 100644 --- a/libs/geom/include/psemek/geom/math.hpp +++ b/libs/geom/include/psemek/geom/math.hpp @@ -2,6 +2,9 @@ #include +#include +#include + namespace psemek::geom { @@ -29,4 +32,20 @@ namespace psemek::geom return x0 * (T(1) - t) + x1 * t; } + // roots of ax^2 + bx + c = 0 + // in increasing order + template + std::optional> solve_quadratic(T const & a, T const & b, T const & c) + { + auto const D = b * b - 4 * a * c; + if (D < 0) return std::nullopt; + + auto t = - (b + (b > 0 ? 1 : -1) * std::sqrt(D)); + auto x1 = t / a; + auto x2 = c / t; + + if (x1 > x2) std::swap(x1, x2); + return std::pair{x1, x2}; + } + }