A Robust High-Precision Quadratic Equation Solver in C++20 for
where
Both single-precision (32-bits) and double-precision (64-bits) are supported.
To use this solver in your project, you can:
- Include the header file QuadraticEquationSolver.h;
- Initialize a
QuadraticEquationSolver
with$a,b,c$ ; - Call the solver method
solve
to get the roots and state!
#include "QuadraticEquationSolver.h"
double a = 1.0, b = 4.0, c = -5.0;
QuadtraticEquationSolver<double> solver(a, b, c);
double x1, x2;
// x1 and x2 will be the two roots! And s is their state.
SolverState s = solver.solve(x1, x2);
- Print the roots and state;
#include <iostream>
std::cout << "x1: " << x1 << std::endl;
std::cout << "x2: " << x2 << std::endl;
// Print the state of the solver itself
std::cout << "State: " << solver.print_solver_state() << std::endl;
// Or print the specified state `s` by the class static method
std::cout << "State: " << QuadtraticEquationSolver<double>::print_solver_state(s) << std::endl;
- You can re-use the solver by
reset
:
a = 1.0, b = 4.0, c = 4.0;
solver.reset(a, b, c); // Clean the solver state and reset a, b, c
s = solver.solve(x1, x2); // Solve the new equation
Requirements:
- CMake >= 3.20
- C++ compiler supporting C++20 standard.
# Make a directory OUTSIDE this source directory and go into it
mkdir ../build
cd ../build
# Use cmake to configure the project with this SOURCE DIRECTORY
cmake ../QuadtraticEquationSolver
# Compile
make
# Run the demo
./demo
# Optional: run the test
make test
# Optional: Compare QuadtraticEquationSolver and a naive non-robust solver
./float_test # For 41 single-precision (32-bits) cases
./double_test # For 41 double-precision (64-bits) cases
See here for more detailed discussion and surprising cases.
Thank the author for developing and sharing this algorithm in the following paper.
Frédéric Goualard. The Ins and Outs of Solving Quadratic Equations with Floating-Point Arithmetic. 2023. ⟨hal-04116310⟩
Based on works by wepik@Freepik
Copyright 2025 Kanition
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.