Skip to content

Commit bcca2fb

Browse files
Added quadratic_equations_complex_numbers.cpp
1 parent 29f5439 commit bcca2fb

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
/**
2+
* @file
3+
* @brief Calculate quadratic equation with complex roots, i.e. b^2 - 4ac < 0.
4+
* @see https://en.wikipedia.org/wiki/Quadratic_equation,
5+
* https://en.wikipedia.org/wiki/Quadratic_equation#discriminant
6+
*
7+
* @author [Renjian-buchai](https://github.com/Renjian-buchai)
8+
*/
9+
10+
#include <array>
11+
#include <cmath>
12+
#include <complex>
13+
#include <exception>
14+
15+
/// @brief Quadratic equation calculator.
16+
/// @param a quadratic coefficient.
17+
/// @param b linear coefficient.
18+
/// @param c constant
19+
/// @return Array containing the roots of quadratic equation, incl. complex
20+
/// root.
21+
std::array<std::complex<long double>, 2> quadraticEquation(long double a,
22+
long double b,
23+
long double c) {
24+
/**
25+
* Calculates any quadratic equation in form ax^2 + bx + c.
26+
*
27+
* Quadratic equation:
28+
* x = (-b +/- sqrt(b^2 - 4ac)) / 2a
29+
*
30+
* e.g.
31+
* using namespace std;
32+
* int main() {
33+
* array<complex<long double, 2> solutions = quadraticEquation(1, 2, 1);
34+
* cout << solutions[0] << " " << solutions[1] << "\n";
35+
*
36+
* solutions = quadraticEquation(1, 1, 1); // Reusing solutions.
37+
* cout << solutions[0] << " " << solutions[1] << "\n";
38+
* return 0;
39+
* }
40+
*
41+
* Output:
42+
* (-1, 0) (-1, 0)
43+
* (-0.5,0.866025) (-0.5,0.866025)
44+
*/
45+
46+
if (a == 0)
47+
throw std::invalid_argument("quadratic coefficient cannot be 0");
48+
49+
long double discriminant = b * b - 4 * a * c;
50+
std::array<std::complex<long double>, 2> solutions{0, 0};
51+
52+
// Complex root (discriminant < 0)
53+
// Note that the left term (-b / 2a) is always real. The imaginary part
54+
// appears when b^2 - 4ac < 0, so sqrt(b^2 - 4ac) has no real roots. So, the
55+
// imaginary component is i * (+/-)sqrt(abs(b^2 - 4ac)) / 2a.
56+
if (discriminant < 0) {
57+
// Since b^2 - 4ac is < 0, for faster computation, -discriminant is
58+
// enough to make it positive.
59+
solutions[0] = std::complex<long double>{
60+
-b * 0.5 / a, -std::sqrt(-discriminant) * 0.5 / a};
61+
solutions[1] = std::complex<long double>{
62+
-b * 0.5 / a, std::sqrt(-discriminant) * 0.5 / a};
63+
} else {
64+
// Since discriminant > 0, there are only real roots. Therefore,
65+
// imaginary component = 0.
66+
solutions[0] = std::complex<long double>{
67+
(-b - std::sqrt(discriminant)) * 0.5 / a, 0};
68+
solutions[1] = std::complex<long double>{
69+
(-b + std::sqrt(discriminant)) * 0.5 / a, 0};
70+
}
71+
72+
return solutions;
73+
}

0 commit comments

Comments
 (0)