Skip to content

Commit 1d20a50

Browse files
authored
Merge pull request #331 from Selbl/cpp-problem-6
Problem 6 - C++ Solution
2 parents 9920eca + fb39269 commit 1d20a50

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
#include <iostream>
2+
#include <vector>
3+
#include <cmath>
4+
#include <cassert>
5+
6+
using namespace std;
7+
8+
vector<double> calculate_eigenvalues(const vector<vector<double> >& matrix)
9+
{
10+
// Extract elements
11+
double a = matrix[0][0];
12+
double b = matrix[0][1];
13+
double c = matrix[1][0];
14+
double d = matrix[1][1];
15+
16+
// Get trace and determinant
17+
double trace = a + d;
18+
double determinant = a * d - b * c;
19+
double discriminant = trace * trace - 4.0 * determinant;
20+
21+
// Solve for eigenvalues
22+
double lambda1 = (trace + sqrt(discriminant)) / 2.0;
23+
double lambda2 = (trace - sqrt(discriminant)) / 2.0;
24+
25+
// Return as vector
26+
vector<double> eigenvalues(2);
27+
eigenvalues[0] = lambda1;
28+
eigenvalues[1] = lambda2;
29+
return eigenvalues;
30+
}
31+
32+
33+
void test_calculate_eigenvalues()
34+
{
35+
// Test Case 1
36+
{
37+
38+
vector<vector<double> > matrix(2, vector<double>(2));
39+
matrix[0][0] = 2.0; matrix[0][1] = 1.0;
40+
matrix[1][0] = 1.0; matrix[1][1] = 2.0;
41+
42+
vector<double> result = calculate_eigenvalues(matrix);
43+
assert(result.size() == 2);
44+
45+
assert(result[0] == 3.0);
46+
assert(result[1] == 1.0);
47+
}
48+
49+
// Test Case 2
50+
{
51+
52+
vector<vector<double> > matrix(2, vector<double>(2));
53+
matrix[0][0] = 4.0; matrix[0][1] = -2.0;
54+
matrix[1][0] = 1.0; matrix[1][1] = 1.0;
55+
56+
vector<double> result = calculate_eigenvalues(matrix);
57+
assert(result.size() == 2);
58+
59+
assert(result[0] == 3.0);
60+
assert(result[1] == 2.0);
61+
}
62+
}
63+
64+
int main()
65+
{
66+
test_calculate_eigenvalues();
67+
return 0;
68+
}

0 commit comments

Comments
 (0)