Add a quadratic solver that assumes real roots
This commit is contained in:
parent
e8219b7139
commit
f9dbc9138f
1 changed files with 21 additions and 0 deletions
|
|
@ -48,4 +48,25 @@ namespace psemek::geom
|
|||
return std::pair{x1, x2};
|
||||
}
|
||||
|
||||
// roots of ax^2 + bx + c = 0
|
||||
// in increasing order
|
||||
// the quadratic is assumed to have real roots
|
||||
template <typename T>
|
||||
std::pair<T, T> solve_quadratic_positive(T const & a, T const & b, T const & c)
|
||||
{
|
||||
auto const D = b * b - 4 * a * c;
|
||||
if (D <= 0)
|
||||
{
|
||||
auto x = - b / (2 * a);
|
||||
return std::pair{x, x};
|
||||
}
|
||||
|
||||
auto t = - (b + (b > 0 ? 1 : -1) * std::sqrt(D)) / 2;
|
||||
auto x1 = t / a;
|
||||
auto x2 = c / t;
|
||||
|
||||
if (x1 > x2) std::swap(x1, x2);
|
||||
return std::pair{x1, x2};
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue